KatInterview

Simulating Motion Under Time-Varying Visibility Constraints

Arrays & HashingModel answer
MediumModel answerArrays & Hashingsimulationbinary-searchprefix-sum

Last 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 t takes effect at the start of step t.
  • 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^5
  • 0 ≤ T ≤ 10^9
  • All positions and times are integers
  • switch_times may 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.