KatInterview

Runners Dodging Bouncing Sentries Along a Track

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationsimulationmodular-arithmeticperiodic-motion

Last updated

Count how many runners, released one per time unit, cross a track without ever sharing a cell at the same integer time with a sentry that bounces back and forth inside a fixed range.

Runners Dodging Bouncing Sentries

A track has cells numbered 0, 1, ..., L. N runners must travel from cell 0 to cell L. Runner k (for k = 0, 1, ..., N-1) enters cell 0 at time k and then moves forward exactly one cell per time unit, so runner k is on cell x at time k + x.

There are M sentries. Sentry i patrols the inclusive range [a_i, b_i]. At time 0 it stands on a_i. It moves toward b_i at one cell per time unit, reverses the moment it arrives, walks back to a_i, reverses again, and repeats forever. A sentry with a_i = b_i never moves.

A runner is caught if, at some integer time and on some cell in 0..L, that runner and at least one sentry occupy the same cell. Only integer times are checked. If a runner and a sentry exchange neighbouring cells between two consecutive time units, that is not a catch.

Return the number of runners that are never caught.

Function signature

def count_safe_runners(N: int, L: int, sentries: list[tuple[int, int]]) -> int:

Example

N = 8, L = 5, sentries = [(1, 3)] returns 4.

The sentry's cell at times 0, 1, 2, 3, 4, ... is 1, 2, 3, 2, 1, ..., which repeats every 4 steps. Runners released at odd times are caught. Runners released at times 0, 2, 4 and 6 get through.

Constraints

  • 1 <= L <= 10^5
  • 1 <= N <= 10^5
  • 1 <= M <= 10^3
  • 0 <= a_i <= b_i <= 10^5
  • All values are integers.

Edge cases to handle

  • Stationary sentries (a_i == b_i).
  • Sentries whose range is partly or entirely beyond cell L.
  • L much smaller than the number of sentries.

What is expected

Give an approach that is clearly better than simulating every runner against every sentry cell by cell. Justify its correctness, state its complexity, and write the code.

Hints

Hint 1

Describe where one sentry is at time t. For b > a it repeats with period P = 2*(b-a). A runner meets it on cell x exactly when the sentry is on x at time k + x.

Hint 2

For a fixed sentry and cell x, the sentry stands on x when t mod P equals u or P - u, where u = x - a. Substitute t = k + x to get conditions on k mod P.

Hint 3

The first condition gives k ≡ -a for every x, and the second gives k ≡ a - 2x. If the whole range [a, b] fits on the track, those residues are exactly all residues with the same parity as a, so the sentry catches every runner whose start time has that parity.