SDE & MLE Prep

1466. Reorder Routes to Make All Paths Lead to the City Zero

Problem

Cities 0…n − 1 are joined by n − 1 one-way roads that would form a tree if undirected; connections[i] = [a, b] is a road from a to b. Return the minimum number of roads to reverse so every city can reach city 0.

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

Constraints: n ≤ 5·10⁴.

Treat roads as undirected but remember direction: an original edge a → b costs 1 when traversed away from 0 (it must be reversed), its reverse costs 0. DFS from 0 summing costs.

Complexity: O(n).

class Solution:
    def minReorder(self, n: int, connections: List[List[int]]) -> int:
        g = defaultdict(list)
        for a, b in connections:
            g[a].append((b, 1))     # original direction, points away from 0 -> needs flip
            g[b].append((a, 0))
        seen, st, flips = {0}, [0], 0
        while st:
            u = st.pop()
            for v, cost in g[u]:
                if v not in seen:
                    seen.add(v)
                    flips += cost
                    st.append(v)
        return flips