Do Two Walkers Ever Share the Same Tile?
Math & Bit ManipulationModel answerLast updated
Determine if two entities moving on an infinite 2D grid ever occupy the same cell at the same integer time step.
Two Walkers on a Grid
Two robots, Alpha and Beta, are placed on an infinite 2D grid. Both begin moving at time t = 0 from their respective starting positions. Each robot follows a sequence of movement commands. A single command is a pair (direction, steps), where direction is one of 'U', 'D', 'L', 'R', and steps is a positive integer. At every integer time tick, the robot advances exactly one unit in the given direction.
Your job is to determine whether there exists any integer time t >= 0 at which both robots are on the exact same grid cell.
Function Signature
def do_walkers_meet(alpha_path, beta_path, alpha_start=(0,0), beta_start=(0,0), include_t0=True) -> bool:
Input
alpha_path: list of(direction, steps)tuples for Alpha.beta_path: list of(direction, steps)tuples for Beta.alpha_start,beta_start: starting coordinates, default(0, 0).include_t0: whethert = 0counts as a valid meeting time (defaultTrue).
Constraints
- The total number of steps across both paths combined is at most 1,000,000.
- Grid coordinates may be any integer (positive, negative, or zero).
- When a robot exhausts its command list, it remains stationary at its last position.
Examples
Example 1
alpha_path = [('R', 2)]
beta_path = [('R', 1), ('D', 1)]
include_t0 = False
Expected output: True
(Both robots are at (1, 0) at t = 1.)
Example 2
alpha_path = [('U', 5)]
beta_path = [('R', 5)]
include_t0 = False
Expected output: False
(They start together at the origin, but t = 0 is excluded. After that they diverge.)
Edge Cases to Consider
- Both robots start at the same position (
include_t0=True→ immediatelyTrue). - Paths of very different lengths (one robot parks early).
- Two robots moving in parallel — they coincide for an entire window.
- Two robots moving toward each other and crossing at a half-integer time (should return
False). - One or both paths are empty (robots never move).
What to Produce
Write a working solution, explain the core approach and its time and space complexity, and discuss how you would handle the follow-up where each robot can move at an arbitrary integer speed per command.
Hints
Hint 1
Start with the brute-force simulation: expand every command into individual ticks and check positions. That runs in O(T) where T is total steps — up to 1,000,000 — which is acceptable but not optimal. Mention it before improving.
Hint 2
Notice that between consecutive command boundaries, both robots move at constant velocity. The relative displacement is therefore a linear function of time within each window. A meeting inside the window is just the question: does this linear function hit zero at an integer k in [lo, hi]?
Hint 3
Merge the two command lists the same way you merge two sorted arrays — always consume the shorter remaining segment. Within each merged window, solve the two-axis linear equations using only integer arithmetic (divisibility check, no floating point). Watch out for the window's inclusive lower bound when t=0 is excluded.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Clarify the contract before coding
Several things need pinning down before the first line of code:
Starting positions. The signature only takes paths, implying both robots start at the origin. Making alpha_start and beta_start explicit parameters handles the general case without changing anything for the default.
Does t = 0 count? The spec says t >= 0, and sharing a start should be True. But Example 2 returns False even though both robots begin at (0, 0). The two are consistent only if t = 0 is excluded in Example 2. The include_t0 flag makes the behavior explicit rather than silent.
What happens after a path ends? The problem says "paths of different total lengths" are an edge case, but doesn't say what happens. The natural reading — the robot parks at its last cell forever — is assumed here.
Crossing between ticks. If Alpha moves (0,0)→(1,0) while Beta moves (1,0)→(0,0), they pass through each other at t = 0.5. That is not a meeting, since only integer times count.
Step 2 — O(T) baseline
Simulate every tick: compute each robot's position and check equality. This is O(T) time and O(1) space, easy to reason about, and fast enough given T ≤ 1,000,000. Always mention it — interviewers want to see you know the simple solution before you optimize.
Step 3 — O(n + m) segment approach
The key insight: between consecutive command boundaries, both robots have constant velocities. The relative displacement is:
delta(k) = d0 + v_rel * k, k = 0, 1, ..., window_length
where d0 = alpha_pos - beta_pos at the window start and v_rel = v_alpha - v_beta. Each component of v_rel is in {-2, -1, 0, 1, 2}.
A meeting happens when delta(k) = (0, 0) for some integer k in the valid range. This is two independent divisibility checks, one per axis:
- If
v == 0: the axis is stuck; we needd == 0, otherwise no solution exists. - If
v != 0: we needk = -d / vto be an integer (checkd % v == 0) and fall in[lo, window_length]. - Both axes must agree on the same
k.
Merge the two command lists like merge sort — always advance through the smaller remaining segment. This visits each command exactly once.
Complexity
- Time: O(n + m) — one pass through all commands, O(1) work per merged window.
- Space: O(1) — two pointers, current positions, no expansion of steps.
Common mistakes
- Floating-point division. Never divide
dbyvwith/; use%and//to stay in exact integer arithmetic. - Window boundary off-by-one. The window covers
kin[0, step]inclusive. Wheninclude_t0=Falseapplies only to the very first window, setlo = 1only there. - Forgetting the parked state. When a robot exhausts its commands, it gets velocity
(0, 0)for all remaining windows. Failing to handle this makes different-length paths incorrect. - Both robots parked at the same cell. If both finish their commands while co-located, they meet at
t = 1(ort = 0ifinclude_t0=True).
Python solution
DIRS = {'U': (0, 1), 'D': (0, -1), 'L': (-1, 0), 'R': (1, 0)}
def _meets_in_window(dx, dy, vx, vy, lo, hi):
"""Return True if dx + vx*k == 0 AND dy + vy*k == 0 for some int k in [lo, hi]."""
k = None
for d, v in ((dx, vx), (dy, vy)):
if v == 0:
if d != 0:
return False
# This axis is satisfied for any k; continue to the other axis.
else:
if d % v != 0:
return False
kk = -d // v
if kk < lo or kk > hi:
return False
if k is not None and k != kk:
return False
k = kk
# k was constrained by at least one axis, or both axes are zero-velocity
# with d == 0, meaning every k works — check the range is non-empty.
return k is not None or lo <= hi
def do_walkers_meet(alpha_path, beta_path,
alpha_start=(0, 0), beta_start=(0, 0),
include_t0=True) -> bool:
ax, ay = alpha_start
bx, by = beta_start
if include_t0 and (ax, ay) == (bx, by):
return True
i = j = 0
a_rem = b_rem = 0
avx = avy = bvx = bvy = 0
first_window = True
while True:
# Advance Alpha to the next non-empty command, or park it.
while a_rem == 0 and i < len(alpha_path):
direction, a_rem = alpha_path[i]
i += 1
avx, avy = DIRS[direction]
if a_rem == 0:
avx = avy = 0
# Advance Beta similarly.
while b_rem == 0 and j < len(beta_path):
direction, b_rem = beta_path[j]
j += 1
bvx, bvy = DIRS[direction]
if b_rem == 0:
bvx = bvy = 0
# Both robots are now parked forever.
if a_rem == 0 and b_rem == 0:
return (ax, ay) == (bx, by)
window = min(r for r in (a_rem, b_rem) if r > 0)
lo = 1 if (first_window and not include_t0) else 0
if _meets_in_window(ax - bx, ay - by, avx - bvx, avy - bvy, lo, window):
return True
ax += avx * window; ay += avy * window
bx += bvx * window; by += bvy * window
if a_rem:
a_rem -= window
if b_rem:
b_rem -= window
first_window = False
Verifying the examples (include_t0=False)
Example 1: First window length 1, both move right, so v_rel = (0, 0) and d0 = (0, 0). Every k in [1, 1] is a solution → True.
Example 2: v_rel = (-1, 1), d0 = (0, 0). Solving gives k = 0, which is outside [1, 5]. No later window works since they diverge → False.
Follow-up: arbitrary integer speeds
Each command becomes (direction, speed, steps). The velocity is speed × unit_vector. The relative velocity can now be larger, but the window equation d0 + v_rel·k = 0 is still linear with integer coefficients. The same divisibility check applies unchanged — just substitute the new v_rel values.
For rational speeds, scale time by the LCM of all denominators to convert every position to integers, then apply the same approach on the rescaled timeline.