Solve Balanced Permutations and Tree Reversals
UberSoftware Engineer · Online AssessmentLast updated
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.
You have 90 minutes to solve the following two independent coding problems.
Problem 1: Balanced Prefix Values in a Permutation
You are given a permutation p of the integers 1 through N.
For each k from 1 to N, consider the positions in p of the values 1, 2, ..., k. Determine whether these k elements occupy one contiguous segment of the original array.
Return a binary string ans of length N, where:
ans[k - 1] = '1'if the positions of values1throughkare contiguous inp.ans[k - 1] = '0'otherwise.
Example
If p = [4, 1, 3, 2]:
- For
k = 1, value{1}appears contiguously, so output1. - For
k = 2, values{1, 2}are at positions2and4, not contiguous, so output0. - For
k = 3, values{1, 2, 3}are at positions2, 3, 4, contiguous, so output1. - For
k = 4, all values occupy the whole array, so output1.
The result is 1011.
Problem 2: Minimum Edge Reversals to Root a Directed Tree
You are given a directed graph with N nodes and N - 1 directed edges. If edge directions are ignored, the graph forms a tree.
You may choose any node as the root. After choosing the root, every edge must point away from the root, meaning every directed edge should go from a parent to a child in the rooted tree.
If an edge points in the wrong direction, you may reverse it. Find the minimum possible number of edge reversals over all choices of the root.
Example
Suppose the directed edges are:
1 -> 2
3 -> 2
3 -> 4
If node 3 is chosen as the root, the edges should point away from 3:
3 -> 2
3 -> 4
2 -> 1
Only edge 1 -> 2 must be reversed, so the answer is 1.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.