Reorder Routes to Make All Paths Lead to City Zero

MediumGraphsdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n cities numbered 0 to n - 1 joined by n - 1 one-way roads, and ignoring direction the roads form a tree (exactly one route between any two cities). Each connections[i] = [a, b] is a road that can only be driven from a to b. The capital is city 0. You want every city to be able to drive to city 0. You may reverse the direction of some roads. Return the minimum number of roads that must be reversed.

Examples

Input: n = 5, connections = [[1,0],[1,2],[3,2],[0,4]]
Output: 2
Roads 1->2 and 0->4 point away from the capital, so they must be flipped. Roads 1->0 and 3->2 already lead toward city 0.
Input: n = 3, connections = [[1,0],[2,0]]
Output: 0
Both roads already end at the capital.

Constraints

  • 2 <= n <= 5 * 10^4
  • connections.length == n - 1
  • 0 <= a, b < n and a != b
  • Ignoring direction, the roads form a tree

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems