Runners Dodging Bouncing Sentries Along a Track
Math & Bit ManipulationModel answerLast 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^51 <= N <= 10^51 <= M <= 10^30 <= 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. Lmuch 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model
Take a sentry with range [a, b], d = b - a > 0, and period P = 2d. With r = t mod P, its cell at time t is a + r if r <= d, otherwise a + P - r.
Runner k is on cell x at time k + x. A collision on cell x requires a <= x <= min(b, L), since the sentry never leaves [a, b] and the track ends at L. Let u = x - a, which lies in [0, d]. The sentry is on x at time t exactly when t mod P is u or P - u. Substituting t = k + x:
k ≡ u - x = -a (mod P)k ≡ -u - x = a - 2x (mod P)
At x = a the second expression equals the first, so the full set of bad start residues for this sentry is
{ (a - 2x) mod P : x = a .. min(b, L) }
The condition t >= 0 holds automatically because t = k + x >= 0.
Stationary sentry. If a == b and a <= L, every runner passes cell a and is caught, so the answer is 0. If a > L the sentry is irrelevant.
Parity shortcut. If b <= L, the cells x = a, a+1, ..., a+d give residues a - 2x, which step down by 2 and wrap around after d steps. That produces all d residues modulo 2d with the same parity as a. Since P is even, the sentry catches exactly the runners whose start time k has the same parity as a. In the example, a = 1 is odd, so the odd runners are caught, which matches.
Truncated sentry. If b > L, only x = a..L count. That is at most d cells, so the residues a - 2x mod P are all distinct. They must be marked one by one.
Algorithm
- Keep a
bytearray badof lengthN. - For each sentry:
- If
a > L, skip it. - If
a == b, return0. - If
b <= L, mark every start time with paritya % 2. - Otherwise set
P = 2*(b-a). For eachxina..L, computer = (a - 2x) mod Pand, ifr < N, markbad[r::P].
- If
- Return
N - sum(bad).
Code
def count_safe_runners(N, L, sentries):
bad = bytearray(N)
for a, b in sentries:
if a > L:
continue
if a == b:
return 0 # a fixed sentry on the track blocks everyone
if b <= L:
s = a & 1 # whole patrol is on the track: parity rule
bad[s::2] = b"\x01" * len(range(s, N, 2))
else:
P = 2 * (b - a)
for x in range(a, L + 1):
r = (a - 2 * x) % P
if r < N:
bad[r::P] = b"\x01" * len(range(r, N, P))
return N - sum(bad)
Check on the example: a = 1, b = 3, L = 5, so b <= L and a is odd. All odd start times in 0..7 are marked, leaving 0, 2, 4, 6, so the result is 4.
Check on a truncated sentry: N = 4, L = 2, sentries = [(1, 3)], so P = 4. For x = 1 the residue is -1 mod 4 = 3, and for x = 2 it is -3 mod 4 = 1. Runners 1 and 3 are caught. By hand, runner 1 is on cell 2 at time 3, where the sentry stands, so it is caught. Runner 0 is on cells 0, 1, 2 at times 0, 1, 2, and the sentry is on 1, 2, 3 at times 0, 1, 2, so runner 0 is safe. The answer is 2.
Complexity
- Each sentry that fits the track costs
O(N)(one strided write). - Each truncated sentry loops over at most
min(d, L - a) + 1cells. Each strided write touches aboutN / Pentries, so the writes total aboutN / 2per sentry. - Overall the worst case is
O(M * (N + L)), roughly2 * 10^8very cheap operations, with the slice writes running in C. Memory isO(N).
The brute force simulates every runner against every sentry over L + 1 steps. That is O(N * M * L), around 10^13, which is hopeless.
Trade-offs and alternatives
- Per-sentry residues (above): each sentry is handled modulo its own period, so no global period is needed.
- Combined period: the whole system repeats with the LCM of all periods. That LCM can be astronomically large, so do not build a table of that length.
- Difference arrays: for the truncated case, residue classes can be turned into arithmetic progressions and marked with a numpy fancy-index or per-residue counters. This reduces constant factors but not the asymptotics.
- Early exit: once every entry is marked, stop and return
0.
Common mistakes
- Using period
dinstead of2d. The sentry must go out and come back. - Treating the turn-around cells
aandbas visited twice per period. They are visited once, which is why the two residue formulas coincide there. Double-marking is harmless, but double-counting is not. - Marking cells outside
[a, min(b, L)]. - Counting a neighbour swap (runner and sentry crossing between time steps) as a catch. The rules say it is not.
- Not special-casing
a == b, which gives a modulus by zero. - In C++ or Java, forgetting to normalise negative remainders. Use
((v % P) + P) % P. - Applying the parity shortcut when
b > L. It only holds when the entire patrol range is on the track.
Follow-ups worth discussing
- If
Nis as large as10^9, the bytearray is impossible. Represent each sentry's bad set as a parity class or a list of residues moduloP. Count safe start times by inclusion-exclusion over the union of arithmetic progressions, or by grouping sentries with the same period. - If runners can move at different speeds
v, the residue equations become linear congruences ink, so you need a modular inverse or a gcd check for solvability. - If a swap between adjacent cells counted as a catch, you would also check the half-step positions. For a sentry that stays on the track, this adds the opposite parity condition for those pairs.