Skip to the code
cf.
+25 XP

#419 Point Every Route at the Hub

medium

A content delivery setup has n servers numbered 0 to n - 1, joined by n - 1 one-way links so that, ignoring direction, every server is connected (the links form a tree). links[i] = [a, b] means data can flow from a to b.

Every server must be able to send data to the hub, server 0. You may flip the direction of any link. Write fewestFlips(n, links) that returns the fewest links you must flip so that every server can reach server 0.

Example 1

Input: n = 5, links = [[0,1],[1,2],[3,1],[3,4]]
Output: 3

Links 0→1, 1→2, and 3→4 point away from the hub and must be flipped. 3→1 already points toward it.

Example 2

Input: n = 3, links = [[1,0],[2,0]]
Output: 0

Both links already point at the hub.

Constraints

  • 1 <= n <= 50000
  • links.length === n - 1
  • Ignoring direction, the links connect all servers.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).