Ctrl K

Three-Lane Runner

Medium
A track has three lanes numbered 1, 2, 3 and is marked with points 0 through n. A runner starts at point 0 in lane 2 and must reach point n in any lane. The array blocks of length n + 1 describes barriers: if blocks[i] = k > 0, lane k is blocked at point i; if blocks[i] = 0, point i is clear. At most one lane is blocked at each point, and points 0 and n are always clear. The runner moves from point i to point i + 1 in the same lane if that lane has no barrier at point i + 1. At any point the runner may also switch to any other lane (not necessarily an adjacent one), as long as that lane is clear at that point. Return the fewest lane switches needed to reach the finish.
Example 1
blocks=[0, 2, 0, 0] → 1

Lane 2 is blocked at point 1, so the runner moves to lane 1 or 3 before it: one change.

Example 2
blocks=[0, 1, 3, 2, 0] → 1

Run in lane 2 up to point 2, switch to lane 1 there and stay in it to the finish: one switch. Some switch is unavoidable, since lane 2 is blocked at point 3.

Example 3
blocks=[0, 1, 1, 3, 0] → 0

Lane 2 is clear the whole way, so no changes are needed.

Constraints
  • 1 ≤ n ≤ 5 · 10⁵, len(blocks) = n + 1
  • 0 ≤ blocks[i] ≤ 3
  • blocks[0] = blocks[n] = 0
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumLongest Seesaw Subsequence MediumFewest Meetings to Cancel Medium
loading Python…
Input
blocks=[0, 2, 0, 0]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 124 tests on the server, hidden ones included.