Magicsheet logo

Reorder Routes to Make All Paths Lead to the City Zero

Medium
66%
Updated 6/1/2025

Reorder Routes to Make All Paths Lead to the City Zero

What is this problem about?

The Reorder Routes to Make All Paths Lead to the City Zero interview question gives you n cities connected by n-1 directed roads forming a tree. You need to reorder the minimum number of roads so that every city can reach city 0 by following roads in their (possibly reversed) directions. The goal is to find the minimum count of roads that need their direction flipped.

Why is this asked in interviews?

This graph problem is asked at Microsoft, Meta, DRW, Amazon, and TikTok because it tests tree/graph traversal combined with directional reasoning. It requires candidates to perform a BFS or DFS from node 0, treating the graph as undirected but tracking edge direction. Edges that point away from node 0 (in the original graph) need to be reversed. This is a real-world analogy for network routing and traffic flow optimization.

Algorithmic pattern used

The pattern is BFS/DFS on an undirected graph with edge direction tracking. Build an adjacency list where each edge is stored with a "cost": original direction edges get cost 1 (must be reversed), and reverse-direction edges get cost 0. Starting from node 0, perform BFS. For each neighbor reachable via a cost-1 edge (original direction, pointing away from 0), increment the reversal count. For cost-0 edges (already pointing toward 0), no reversal needed.

Example explanation

n=6, connections: [[0,1],[1,3],[2,3],[4,0],[4,5]]

Build undirected adjacency with direction costs:

  • 0→1 (cost 1), 1→0 (cost 0)
  • 1→3 (cost 1), 3→1 (cost 0)
  • 2→3 (cost 1), 3→2 (cost 0)
  • 0→4 (cost 0), 4→0 (cost 1)
  • 4→5 (cost 1), 5→4 (cost 0)

BFS from 0. Explore edges:

  • 0→1 (cost 1): reverse needed. Count=1.
  • 1→3 (cost 1): reverse needed. Count=2.
  • 3→2 (cost 0): no reverse.
  • 4→0 (cost 0 from 0's side): no reverse.
  • 4→5 (cost 1): reverse needed. Count=3.

Answer: 3.

Common mistakes candidates make

  • Building only a directed graph and missing the need for undirected BFS.
  • Confusing which direction needs reversal — edges pointing AWAY from node 0 in the traversal need flipping.
  • Not marking nodes as visited, causing infinite BFS loops in the undirected representation.
  • Using DFS with recursion on large trees, risking stack overflow — BFS is safer.

Interview preparation tip

For the Reorder Routes to Make All Paths Lead to the City Zero coding problem, the BFS and graph interview pattern with edge cost tracking is the key. Build your adjacency list as undirected but tag each edge with its original direction. BFS from node 0 and count cost-1 edges. Practice this pattern on other "tree rerouting" problems. Interviewers at DRW and Docusign appreciate candidates who immediately recognize the undirected BFS with edge-direction cost as the right framework.

Similar Questions