Solve Balanced Permutations and Tree Reversals
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This two-part prompt evaluates array and permutation reasoning for detecting contiguous value ranges and directed graph/tree reasoning for minimizing edge reversals when choosing a root, testing competencies in index and interval management, graph traversal and orientation, and algorithmic counting.
Part 1: Balanced Prefix Values in a Permutation
Constraints
- 1 <= N <= 2 * 10^5
- `p` is a permutation of `1..N`
- The solution should run in linear time
Examples
Input: [4, 1, 3, 2]
Expected Output: '1011'
Explanation: Positions of `1,2,3,4` are `2,4,3,1` in 1-based indexing. The sets for `k=1,2,3,4` are contiguous, not contiguous, contiguous, contiguous.
Input: [1, 2, 3, 4]
Expected Output: '1111'
Explanation: Each prefix of values already occupies the first `k` positions.
Input: [2, 1, 4, 3]
Expected Output: '1101'
Explanation: For `k=3`, the values `1,2,3` appear at positions `2,1,4`, which do not form one segment.
Input: [1]
Expected Output: '1'
Explanation: Single-element permutation: the only value is trivially contiguous.
Input: [3, 1, 2, 5, 4]
Expected Output: '11101'
Explanation: Values `1,2,3` occupy positions `2,3,1`, which are contiguous together, but adding `4` breaks contiguity until all five values are included.
Hints
- Instead of scanning the permutation for each `k`, first compute where each value appears.
- For values `1..k`, they are contiguous exactly when `max_position - min_position + 1 == k`.
Part 2: Minimum Edge Reversals to Root a Directed Tree
Constraints
- 1 <= n <= 2 * 10^5
- `len(edges) == n - 1`
- If directions are ignored, the graph formed by `edges` is a tree
- Node labels are integers from `1` to `n`
Examples
Input: (4, [(1, 2), (3, 2), (3, 4)])
Expected Output: 1
Explanation: Choosing node `3` as root requires only reversing edge `1 -> 2` into `2 -> 1`.
Input: (1, [])
Expected Output: 0
Explanation: Edge case: a single node has no edges, so no reversals are needed.
Input: (3, [(1, 2), (2, 3)])
Expected Output: 0
Explanation: Choosing node `1` as root already makes all edges point away from the root.
Input: (3, [(2, 1), (2, 3)])
Expected Output: 0
Explanation: Choosing node `2` as root already gives the correct outward orientation.
Input: (5, [(2, 1), (2, 3), (4, 3), (5, 3)])
Expected Output: 2
Explanation: No matter which root is chosen, at least two edges must be reversed. For example, rooting at `2` requires reversing `4 -> 3` and `5 -> 3`.
Hints
- First, fix an arbitrary root such as node `1` and count how many edges are wrong for that root.
- When you move the root across one edge, the total answer changes by exactly `+1` or `-1` depending on that edge's original direction.