Problem · Graph

Minimum Route Reversals to Warehouse Zero

Learn this problem
MediumMyntra logoMyntraINTERNONSITE INTERVIEW

Problem statement

There are n warehouses labeled from 0 to n - 1 and n - 1 directed routes. Each route [from, to] permits travel from from to to.

The routes form a tree when their directions are ignored. Reverse the fewest routes so every warehouse has a directed path to warehouse 0. Return that minimum number.

Function

minRouteReversals(n: int, routes: int[][]) → int

Examples

Example 1

n = 6routes = [[0,1],[1,3],[2,3],[4,0],[4,5]]return = 3

The routes from 0 to 1, from 1 to 3, and from 4 to 5 point away from warehouse 0 in the rooted tree and must be reversed.

Example 2

n = 3routes = [[1,0],[2,0]]return = 0

Both nonzero warehouses already have a direct route to warehouse 0.

Constraints

  • 2 <= n <= 10^5.
  • routes.length == n - 1.
  • Every route contains two distinct labels in [0, n - 1].
  • The routes form one tree when directions are ignored.

More Myntra problems

drafts saved locally
public int minRouteReversals(int n, int[][] routes) {
    // Return the minimum number of directed routes to reverse.
}
n6
routes[[0,1],[1,3],[2,3],[4,0],[4,5]]
expected3
checking account