Simulating Motion Under Time-Varying Visibility Constraints
Arrays & HashingModel answerLast updated
Determine how many entities moving rightward on a line reach a target position when their movement is blocked by a direction-switching observer.
You're modeling movement on a one-dimensional line with coordinates increasing to the right. The line has a target boundary at position L.
There are N entities starting at positions p[0], p[1], ..., p[N-1]. A stationary observer is placed at position W.
Each entity attempts to move rightward at a rate of one unit per time step. The simulation runs for T discrete time steps (step 0, step 1, ..., step T-1).
The observer begins facing either left or right (specified by initial_direction). At certain times given in the array switch_times, the observer reverses their facing direction.
Movement rules:
- During each time step, every entity tries to advance one unit to the right.
- An entity that is currently visible to the observer cannot move during that step (it is blocked).
- The observer's visibility works as follows:
- When facing right, the observer sees all entities strictly to their right (position > W).
- When facing left, the observer sees all entities strictly to their left (position < W).
- An entity exactly at position W is not visible and can always move.
- A direction switch at time
ttakes effect at the start of stept. - Once an entity reaches position
L, it stops and is counted as having arrived.
Task: Return the count of entities that reach position L within the T time steps.
Constraints:
1 ≤ N ≤ 10^50 ≤ T ≤ 10^9- All positions and times are integers
switch_timesmay contain duplicates or values outside[0, T)
Follow-up: How would your approach change if time were continuous rather than discrete, with entities moving at constant velocity except when blocked?
Hints
Hint 1
Each entity's journey is independent—solve for one entity at a time based only on the observer's direction schedule.
Hint 2
Precompute prefix sums of left-facing and right-facing time across the observer's direction segments, then use binary search to find when an entity accumulates enough movement time.
Hint 3
An entity left of W needs right-facing time to reach W, then left-facing time to reach L; an entity right of W only needs left-facing time.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight: Independence
Entities never affect each other. Each entity's ability to move depends solely on its own position relative to the observer and the observer's current direction. This means we can solve for each entity independently.
Breaking Down Movement by Region
Consider one entity starting at position p relative to observer position W:
Case 1: Entity starts left of W (p < W)
- Blocked when observer faces left
- Moves during right-facing time
- Needs
W - punits of right-facing time to reach W - Then needs
L - Wunits of left-facing time to reach L
Case 2: Entity starts exactly at W (p == W)
- Never blocked (not visible in either direction)
- Takes one step to reach W + 1
- Then follows Case 3
Case 3: Entity starts right of W (p > W)
- Blocked when observer faces right
- Moves during left-facing time
- Needs
L - punits of left-facing time to reach L
Efficient Time Calculation
Rather than simulating step-by-step (which would be O(N·T) and infeasible when T ≈ 10^9), we preprocess the observer's direction schedule:
-
Build direction segments: The observer's direction is piecewise constant between switch times. Create segments
[start, end, direction)covering[0, T). -
Compute prefix sums: For both left-facing and right-facing time, build prefix sums showing cumulative time of each direction type up to each segment boundary.
-
Query functions:
F(t, dir): Total time spent facingdirduring[0, t)— O(log C) via binary searchinv(amount, dir): Earliest time when cumulativedir-facing time reachesamount— O(log C)
-
Phase simulation: For each entity, compute when it would complete each required phase (right-facing movement, left-facing movement). If the final phase completes by time T, count the entity.
Complexity
- Time: O(C log C + N log C) where C is the number of switches. Sorting switches and then O(log C) lookups per entity.
- Space: O(C) for segments and prefix arrays.
This is dramatically better than O(N·T) simulation when T is large.
Edge Cases
- Entities starting at or beyond L count immediately
- Observer at or beyond L simplifies which phases are needed
- Switch times at t=0 effectively flip the initial direction
- Duplicate switches cancel out (two flips = no flip)
- Switches at t ≥ T are ignored
- Entity might never accumulate enough facing-away time before T expires
Implementation
from bisect import bisect_left, bisect_right
from math import inf
from typing import List
def count_arrivals(L: int, positions: List[int], W: int, T: int,
initial_direction: str, switch_times: List[int]) -> int:
"""
initial_direction: 'L' or 'R'
Returns count of entities reaching position L within T steps.
"""
if T == 0:
return sum(1 for p in positions if p >= L)
opposite = {'L': 'R', 'R': 'L'}
# Build piecewise-constant direction segments covering [0, T)
segments = []
current_time = 0
direction = initial_direction
for switch in sorted(switch_times):
if switch >= T:
break
if switch <= 0:
continue
segments.append((current_time, switch, direction))
current_time = switch
direction = opposite[direction]
segments.append((current_time, T, direction))
# Prefix sums: cumulative left-facing and right-facing time
segment_starts = [seg[0] for seg in segments]
prefix = {'L': [0], 'R': [0]}
for start, end, dirn in segments:
duration = end - start
for d in ['L', 'R']:
prefix[d].append(prefix[d][-1] + (duration if dirn == d else 0))
def cumulative_time(until_time, facing):
"""Total time spent facing `facing` during [0, until_time)."""
if until_time >= T:
return prefix[facing][-1]
seg_idx = bisect_right(segment_starts, until_time) - 1
start, end, dirn = segments[seg_idx]
base = prefix[facing][seg_idx]
if dirn == facing:
base += min(until_time, end) - start
return base
def time_when_accumulated(target_amount, facing):
"""Earliest time when cumulative `facing` time reaches target_amount."""
if target_amount <= 0:
return 0
seg_idx = bisect_left(prefix[facing], target_amount)
if seg_idx >= len(prefix[facing]):
return inf
start = segments[seg_idx - 1][0]
deficit = target_amount - prefix[facing][seg_idx - 1]
return start + deficit
def complete_phase(start_time, needed_distance, facing):
"""Time when a phase starting at start_time completes."""
if needed_distance <= 0:
return start_time
already_accumulated = cumulative_time(start_time, facing)
total_needed = already_accumulated + needed_distance
return time_when_accumulated(total_needed, facing)
count = 0
for pos in positions:
if pos >= L:
count += 1
continue
time = 0
current_pos = pos
# Phase 1: If left of W, need right-facing time to reach W
if current_pos < W:
distance_to_W = min(W - current_pos, L - current_pos)
time = complete_phase(time, distance_to_W, 'R')
current_pos += distance_to_W
if time > T or current_pos >= L:
if current_pos >= L and time <= T:
count += 1
continue
# Phase 2: Pass through W (instant, no blocking)
if current_pos == W:
time += 1
current_pos = W + 1
if time > T:
continue
if current_pos >= L:
count += 1
continue
# Phase 3: If right of W, need left-facing time to reach L
if current_pos < L:
distance_to_L = L - current_pos
time = complete_phase(time, distance_to_L, 'L')
if time <= T:
count += 1
return count
Follow-Up: Continuous Time
In continuous time, entities move at velocity 1.0 whenever not blocked, rather than in discrete steps.
Key changes:
- The position W has measure zero, so entities pass through it instantaneously—no separate "+1 step" phase is needed.
- All arithmetic becomes real-valued, but the segment/prefix-sum structure remains identical.
- An entity left of W needs exactly
(W - p)units of right-facing time followed by(L - W)units of left-facing time.
The algorithm structure is unchanged: preprocess direction segments, use prefix sums and binary search to find when required movement time is accumulated. Complexity remains O((N + C) log C).
Common Mistakes
- Simulating step-by-step when T is large (times out)
- Forgetting that entities at position W are not blocked
- Mishandling switch times outside [0, T) or at boundaries
- Not accounting for entities that start at or beyond L
- Incorrect visibility rules (using ≥ instead of > for "strictly to the right")