Reorder Routes to Make All Paths Lead to the City Zero, explained

To solve Reorder Routes to Make All Paths Lead to the City Zero, treat the roads as an undirected tree, traverse it once starting from city 0, and count every road whose original direction points away from city 0. Those are exactly the roads that must be reversed, and the count is the minimum. The traversal is O(n) time and O(n) space.

By Published 8 min read

The problem in plain words

A country has n cities numbered 0 to n - 1 and exactly n - 1 roads. Every road is one-way: the pair [a, b] means you can drive from a to b but not back. If you ignore the arrows, the roads connect all cities with no loops, so the map is a tree. A big event is taking place in city 0, and everyone must be able to drive there. You may reverse the direction of any road. Return the smallest number of reversals that makes city 0 reachable from every city.

Maps written for this page
nRoadsAnswerWhy
4[0,1], [2,1], [3,2]1Only 0 to 1 points away from city 0. City 3 drives to 2, then 1, and once 0 to 1 is flipped, on to 0.
3[1,0], [2,0]0Both roads already lead into city 0.
3[0,1], [1,2]2A chain pointing the wrong way. Both roads must flip.
5[1,0], [1,2], [3,2], [4,3]1Only the road from 1 to 2 points outward.
1none0A single city is already where it needs to be.
Maps written for this page. Scroll sideways on a small screen.

Confirm that the undirected map is always a tree, because that is what makes the answer unique and simple. If there could be extra roads or loops, you would need a shortest-path model such as 0-1 BFS instead. Also check whether cities are guaranteed to be numbered 0 to n - 1 with no gaps.

The key observation

In a tree, there is exactly one route between any city and city 0. So for every city to reach city 0, every road on every such route must point toward city 0. Since every road lies on the route from its farther end to city 0, every single road must point toward city 0. A road points the wrong way exactly when it goes from the end nearer to city 0 to the end farther from it. The answer is just the number of such roads. No choices are involved, which is why there is no need for search over options or dynamic programming.

Slow approach: measure each road separately

Build an undirected adjacency list. For each road [a, b], find the distance from city 0 to a and to b with a BFS. If b is farther than a, the road points outward and must flip. There are n - 1 roads and each search costs O(n), so the total is O(n²). It is correct, and it shows you understand the observation, but it repeats the same search for every road.

from collections import deque

def reversals_slow(n, roads):
    nbrs = [[] for _ in range(n)]
    for a, b in roads:
        nbrs[a].append(b)
        nbrs[b].append(a)

    def depth(city):
        dist = {0: 0}
        queue = deque([0])
        while queue:
            u = queue.popleft()
            if u == city:
                return dist[u]
            for v in nbrs[u]:
                if v not in dist:
                    dist[v] = dist[u] + 1
                    queue.append(v)
        return -1

    return sum(1 for a, b in roads if depth(b) > depth(a))
Slow version: a fresh distance search for every road.

The obvious fix is to compute all depths with one BFS and then compare. That is already O(n). The main approach goes one step further and does the comparison during the traversal itself, so no depth array is needed.

Main approach: one traversal with direction tags

Store each road twice in the adjacency list. From a, record the neighbor b with a tag of 1, meaning this road already runs from a to b. From b, record the neighbor a with a tag of 0, meaning the road runs the other way. Now start at city 0 and explore the tree. Every time you step from a visited city u to a new city v, you are moving away from city 0. If the tag on that step is 1, the original road also runs from u toward v, which is away from city 0, so it must be reversed. Add the tag to the total.

def reversals(n, roads):
    nbrs = [[] for _ in range(n)]
    for a, b in roads:
        nbrs[a].append((b, 1))  # stored direction a -> b
        nbrs[b].append((a, 0))  # reverse of the stored direction
    seen = [False] * n
    seen[0] = True
    stack = [0]
    flips = 0
    while stack:
        u = stack.pop()
        for v, outward in nbrs[u]:
            if not seen[v]:
                seen[v] = True
                flips += outward
                stack.append(v)
    return flips
Python: iterative DFS from city 0, O(n) time and space.
function reversals(n, roads) {
  const nbrs = Array.from({ length: n }, () => []);
  for (const [a, b] of roads) {
    nbrs[a].push([b, 1]);
    nbrs[b].push([a, 0]);
  }
  const seen = new Uint8Array(n);
  seen[0] = 1;
  const stack = [0];
  let flips = 0;
  while (stack.length > 0) {
    const u = stack.pop();
    for (const [v, outward] of nbrs[u]) {
      if (!seen[v]) {
        seen[v] = 1;
        flips += outward;
        stack.push(v);
      }
    }
  }
  return flips;
}
JavaScript: the same traversal with an explicit stack.

An explicit stack matters here. A map shaped like a single long chain of 50,000 cities is a valid tree, and a recursive DFS would go that many calls deep. BFS with a queue works equally well, since the order of exploration does not change which roads point outward.

A variant without tags

Some candidates store the original roads in a set of pairs and, when stepping from u to v, check whether (u, v) is in the set. It gives the same answer, with hashing overhead per step. The tag version is cheaper and easier to read, so it is the one to write first.

Tracing the five-city map

  1. Build tagsRoads 1 to 0, 1 to 2, 3 to 2 and 4 to 3. From 0, neighbor 1 has tag 0, because the road runs 1 to 0.
  2. Visit 1Tag 0, no flip. From 1, neighbor 2 has tag 1, because the road runs 1 to 2.
  3. Visit 2Tag 1, so this road points away from city 0. Flips = 1.
  4. Visit 3 and 4From 2, neighbor 3 has tag 0. From 3, neighbor 4 has tag 0. No more flips. The answer is 1.

Complexity

n cities and n - 1 roads
ApproachTimeExtra space
Search per road for depthsO(n²)O(n)
One BFS for depths, then compareO(n)O(n)
One traversal with direction tagsO(n)O(n)
n cities and n - 1 roads. Scroll sideways on a small screen.

Edge cases to test

  • A single city with no roads: the answer is 0.
  • Every road already points to city 0: the answer is 0.
  • Every road points away, such as a star with city 0 in the middle and all arrows outward: the answer is n - 1.
  • A long chain, which tests that the traversal is iterative.
  • City 0 as a leaf rather than the center, so the traversal must still cover the whole tree from that end.
  • Roads listed in random order, so code that assumes parents appear before children fails.

Common mistakes

  • Following only the original directed edges from city 0. You never reach most cities that way, because the correct roads point toward city 0, not away from it.
  • Swapping the tags so you count roads that point toward city 0, which returns n - 1 minus the answer.
  • Counting a road twice because it appears in both adjacency lists. The visited check ensures each road is crossed once.
  • Reaching for Dijkstra or 0-1 BFS. They work, but on a tree they add complexity for no benefit.
  • Recursive DFS in Python on deep inputs without raising the recursion limit.

What a good explanation sounds like

Fictional example

From observation to code
Candidate
Ignoring direction, the roads form a tree, so each city has exactly one route to city 0. That means every road has to point toward city 0, and I just need to count the ones that point away.
Candidate
I will store each road in both directions with a tag: 1 for the original direction, 0 for the reverse. Exploring from city 0 always moves outward, so when I cross a road with tag 1 it points away and must flip.
Candidate
That is one pass over n cities and n - 1 roads, so linear time and space. I am using a stack instead of recursion so a long chain does not overflow.

More from this batch

All Paths From Source to Target is another directed-graph walk, this time listing every route instead of fixing edges. Count Servers That Communicate is a reminder that some problems that look like graph search need only counting. Trees and adjacency lists are reviewed on the data structure interview questions page.

Natively during prep

In your own practice on tree and graph problems, Natively can read the statement from a screenshot and point toward an approach, which you can compare against the observation you reached yourself. It also produces a transcript of a mock interview on your computer, so you can confirm you explained why every road must point toward the root before writing code. See how AI can help with coding interviews.

Questions people ask

How do you solve Reorder Routes to Make All Paths Lead to the City Zero?

Treat the roads as an undirected tree and traverse it from city 0. Each road you cross in its original direction points away from city 0 and must be reversed, so count those. It runs in O(n) time.

Why is counting outward roads the minimum?

In a tree each city has exactly one route to city 0, so every road must point toward city 0. Each outward road has to be flipped, and no other road needs to be, so the count is forced.

Should I use BFS or DFS for this problem?

Either one works, since the order of exploration does not change which roads point outward. Use an explicit stack or queue so a long chain of cities cannot overflow the call stack.

What do the direction tags in the adjacency list mean?

Each road is stored twice. The copy in its original direction gets tag 1 and the reversed copy gets tag 0. Walking outward from city 0 along a tag-1 copy means that road needs reversing.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP