Implement stack variants and upward path sum
Company: Bytedance
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: A four-part ByteDance Data Scientist onsite coding question: implement an O(1) MinStack, a MaxStack with peekMax/popMax, a streaming median finder, and a binary-tree upward (node-to-ancestor) path-sum check. It tests data-structure augmentation, streaming order statistics, and prefix-sum tree reasoning.
MinStack Operations
Constraints
- operations contain push/pop/top/getMin
Examples
Input: ((('push', 3), ('push', 1), ('getMin',), ('push', 2), ('top',), ('pop',), ('getMin',)),)
Expected Output: [1, 2, 2, 1]
Explanation: Minimum tracks stack state.
Input: ((('getMin',), ('pop',)),)
Expected Output: [None, None]
Explanation: Empty stack operations return None.
Input: ((('push', 5), ('push', 5), ('pop',), ('getMin',)),)
Expected Output: [5, 5]
Explanation: Duplicate minimum.
Hints
- Maintain a parallel stack of minimum values.
MaxStack Operations
Constraints
- For this grader, a list implementation is acceptable
Examples
Input: ((('push', 5), ('push', 1), ('push', 5), ('top',), ('popMax',), ('top',), ('peekMax',), ('pop',), ('top',)),)
Expected Output: [5, 5, 1, 5, 1, 5]
Explanation: Standard MaxStack behavior.
Input: ((('popMax',), ('push', 2), ('peekMax',)),)
Expected Output: [None, 2]
Explanation: Empty popMax returns None.
Input: ((('push', 3), ('push', 3), ('popMax',), ('pop',)),)
Expected Output: [3, 3]
Explanation: Tie removes the topmost maximum.
Hints
- Track the stack order; popMax scans from the top for the maximum.
Median of a Data Stream
Constraints
- nums may contain duplicates and negatives
Examples
Input: ([1, 2, 3],)
Expected Output: [1.0, 1.5, 2.0]
Explanation: Increasing stream.
Input: ([5, 15, 1, 3],)
Expected Output: [5.0, 10.0, 5.0, 4.0]
Explanation: Even and odd counts.
Input: ([-1, -2, -3],)
Expected Output: [-1.0, -1.5, -2.0]
Explanation: Negative numbers.
Input: ([],)
Expected Output: []
Explanation: Empty stream.
Hints
- Keep a max-heap for the lower half and a min-heap for the upper half.
Upward Path Sum in a Binary Tree
Constraints
- level_order uses None for missing nodes
Examples
Input: ([1, 2, 3, 4, 5], 7)
Expected Output: True
Explanation: Path 2 -> 5 upward has sum 7.
Input: ([1, -2, 3, None, 4], 2)
Expected Output: True
Explanation: Path -2 -> 4 has sum 2.
Input: ([5], 5)
Expected Output: True
Explanation: Single node path.
Input: ([], 1)
Expected Output: False
Explanation: Empty tree.
Hints
- An upward path is the reverse of a suffix of the current root-to-node path.