Compute tree right view and target-sum subarrays
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Overview: This two-part question evaluates skills in tree traversal and visible-node extraction for the binary-tree right-side view task and in array cumulative-sum reasoning for counting contiguous subarrays with a target sum, assessing data-structure manipulation and algorithmic problem-solving competency.
Part 1: Right-Side View of a Binary Tree
Constraints
- 0 <= number of list entries <= 10^4
- Node values are 32-bit signed integers
- The input list is a valid level-order encoding of a binary tree
- The tree may be empty and does not need to be balanced
Examples
Input: [10, 5, 20, 3, 7, None, 30]
Expected Output: [10, 20, 30]
Explanation: The rightmost node at each depth is 10, then 20, then 30.
Input: [1, 2, 3, None, 5, None, 4]
Expected Output: [1, 3, 4]
Explanation: At level 2, node 3 hides node 2 from the right. At level 3, node 4 is the rightmost visible node.
Hints
- A breadth-first traversal lets you process the tree level by level; the last node you visit in each level is the visible one.
- An alternative is depth-first search that visits right children before left children and records the first node seen at each depth.
Part 2: Count Subarrays With a Given Sum
Constraints
- 0 <= n <= 10^5
- Each element of nums is a 32-bit signed integer
- k is a 32-bit signed integer
- An O(n) or near-O(n) solution is expected
Examples
Input: ([1, 2, 3], 3)
Expected Output: 2
Explanation: The valid subarrays are [1, 2] and [3].
Input: ([1, 1, 1], 2)
Expected Output: 2
Explanation: The subarrays [1, 1] at indices (0,1) and (1,2) both sum to 2.
Hints
- Track a running prefix sum as you scan the array.
- If `current_sum - k` has appeared before, then each previous occurrence marks a subarray ending at the current index with sum `k`.