← Uber Interview Insights

Uber·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
Jun 2026

Summary

Uber coding interview with a tree rerooting problem that looks manageable until you actually try to implement it cleanly under pressure. The key gotcha is recursion depth on large inputs, which I did not see coming.

Questions Asked (1)

Q1

Given a tree of n nodes represented as directed edges, for each possible root node compute the minimum number of edge reversals required so that every other node is reachable from that root. Return an array of answers, one per node.

Algorithms & Data Structures
Author's notes

I got the basic idea pretty quick: root the tree at node 0, count reversals needed, then reroot by adjusting the count as you move the root along each edge.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

First, compute the answer for an arbitrary root using a DFS/BFS that counts edges that need reversal. Then, use rerooting DP: when moving the root from parent to child, the answer changes by +1 if the edge is directed parent→child (since it becomes reversed) and -1 if directed child→parent. Propagate these deltas to get all answers in O(n).

Pro tip: Clarify that the tree is undirected in structure but edges have directions; the goal is to orient all edges toward the root. Mention that the rerooting technique generalizes to many tree problems and is a common Uber interview pattern.

1. Model the tree and define cost

Treat the given directed edges as an undirected tree with a direction attribute. For a fixed root, the cost is the number of edges whose direction points away from the root (i.e., need reversal to point toward the root).

2. Compute cost for one root

Pick an arbitrary root (e.g., node 0) and run a DFS/BFS to count how many edges are directed away from it. This gives the answer for that root in O(n).

3. Derive rerooting transition

When moving the root from u to its neighbor v, the edge (u,v) flips its contribution: if it was directed u→v, it now needs reversal (+1); if v→u, it no longer needs reversal (-1). All other edges' contributions remain unchanged.

4. Propagate answers via DFS

Perform a second DFS from the initial root, updating the cost using the transition rule. Store the cost for each node as you visit it.

5. Return the array of answers

After the second DFS, you have the minimum reversals for every node as root. Return them in order.

Key Points to Mention

  • Rerooting dynamic programming technique
  • Time complexity O(n) and space complexity O(n)
  • Handling directed edges as undirected with direction flags
  • The delta change when rerooting: +1 for parent→child, -1 for child→parent
  • Using iterative DFS to avoid recursion depth issues
  • Edge cases: n=1, star graphs, path graphs

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