← Uber Interview Insights

Uber·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
Apr 2026

Summary

Uber SWE interview with a graph problem that looks deceptively clean on the surface. One question, tree structure, but the edge-reversal angle makes you think harder than you'd expect.

Questions Asked (1)

Q1

You're given a directed tree with N nodes and N-1 edges. Pick a root node such that the number of edges you need to reverse (so all edges point away from the root) is minimized. Return that minimum count.

Algorithms & Data Structures
Author's notes

My first instinct was to just BFS from every node and count reversals each time, which technically works but is way too slow.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model the tree with directed edges and compute for each node the number of reversals needed if it were the root. Use a two-pass DFS: first compute the cost for an arbitrary root, then reroot to propagate costs to children in O(N) time.

Pro tip: Clarify that the tree is directed but we can reverse edges; the optimal root minimizes the number of edges pointing toward it. Mention that the rerooting technique is a common pattern in tree DP problems and can be extended to other similar problems.

1. Understand the problem

Restate the problem: given a directed tree, choose a root to minimize the number of edges that must be reversed so all edges point away from the root. Confirm that edges can be reversed at a cost of 1 each.

2. Choose an arbitrary root and compute initial cost

Pick any node (e.g., node 0) as the root. Perform a DFS to count how many edges are directed toward the root (i.e., need reversal) to make all edges point away from it. This gives the cost for that root.

3. Reroot to compute costs for all nodes

Use a second DFS to propagate the cost to children. When moving the root from parent to child, the cost changes by +1 if the edge was originally directed parent→child (since it now points toward the new root), and -1 if it was child→parent (since it now points away).

4. Find the minimum cost

After computing costs for all nodes, return the minimum value. This is the answer.

Key Points to Mention

  • Tree DP with rerooting technique
  • Time complexity O(N) and space complexity O(N)
  • Handling directed edges and reversal cost
  • Avoiding brute-force O(N^2) by using two-pass DFS
  • Edge cases: N=1 (cost 0), star graphs, chains
  • Proof of correctness: cost changes by ±1 when rerooting

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.