Flip the Fewest One-Way Signs

Easy · Topological Sort & Shortest Paths · about 15 min

A delivery van must get from town src to town dst. There are n towns, numbered 0 to n - 1. Each [a, b] in roads is a one-way road from a to b.

Driving a road in its own direction is free. Driving it the wrong way is allowed only after flipping its sign, which costs 1. Return the fewest flips needed to get from src to dst, or -1 if the towns are not connected at all (even with flips). If src == dst the answer is 0.

  • 1 <= n <= 10^5, roads may repeat.

Example: fewest_sign_flips(4, [[0, 1], [2, 1], [2, 3]], 0, 3) → 1 (drive 0 → 1, flip the sign of road 2 → 1 to drive 1 → 2, then drive 2 → 3).

Hints

  • Turn each road into two moves with different costs. What are the two costs?
  • Every move costs 0 or 1. A deque lets you handle the cost-0 moves first without a heap.
  • Only update a town when you found a strictly cheaper cost for it, and never give up on a town just because it was seen before.

Learn the pattern first: the Topological Sort & Shortest Paths lesson.

More Topological Sort & Shortest Paths problems