Earliest Disc Overlap Among Unicycle-Driven Agents
Math & Bit ManipulationAuto-graded · 17 test casesLast updated
Simulate several disc-shaped agents with forward Euler unicycle motion and report the first time step at which any pair overlaps, with all pairs at that step.
Overlapping Robots on a Plane
A fleet of circular robots moves on a flat 2D surface. Each robot is described by an id, a center position (x, y), a heading theta in radians (counter-clockwise from the positive x-axis), and a positive radius.
Every robot follows a unicycle motion model. At each time step k (for k = 0, 1, ..., steps - 1), robot i is given a command (v, omega): a forward speed v and a turn rate omega. The state is advanced by one forward Euler step of length dt:
x_next = x + v * cos(theta) * dt
y_next = y + v * sin(theta) * dt
theta_next = theta + omega * dt
The position update uses the heading from before the update. Robots do not influence each other's motion.
Overlap rule
Two different robots overlap at a given moment if the distance between their centers is less than or equal to the sum of their radii. Touching exactly counts as an overlap.
The state is inspected at the initial moment (step 0) and again after each update (steps 1, 2, ..., steps).
Task
Write a function that simulates the fleet and finds the earliest step at which at least one pair of robots overlaps.
Return a two-element list [first_step, pairs] where:
first_stepis that earliest step index.pairsis a list of all pairs of robot ids that overlap at that step, each pair given as[smaller_id, larger_id], with the list sorted in ascending lexicographic order.
Pairs that only start overlapping at a later step are not included. Return None if no overlap occurs at any step from 0 to steps inclusive.
Notes:
- Ids are not necessarily in increasing order in the input list, so order each pair by id value, not by list position.
- If the robots already overlap at step
0, return step0without applying any commands. - If
steps = 0, only the initial state is checked. controls[i][k]holds the(v, omega)command for thei-th robot inagentsat stepk.- To match the expected results exactly, compare squared distance to squared radius sum, and compute the updates in the order given above.
Constraints
- There are at least 2 robots.
steps >= 0, and eachcontrols[i]has length exactlysteps.dt > 0.- Every radius is strictly positive.
- Coordinates, speeds and turn rates are finite floats (they may be negative).
- Robot ids are distinct integers.
Examples
Example 1
Input: find_first_collision([{'id': 0, 'x': 0, 'y': 0, 'theta': 0, 'radius': 1}, {'id': 1, 'x': 5, 'y': 0, 'theta': 3.141592653589793, 'radius': 1}], [[[2, 0], [2, 0]], [[2, 0], [2, 0]]], 1, 2)
Output: [1, [[0, 1]]]
Example 2
Input: find_first_collision([{'id': 10, 'x': 0, 'y': 0, 'theta': 0, 'radius': 0.5}, {'id': 20, 'x': 10, 'y': 10, 'theta': 1.57, 'radius': 0.5}], [[[1, 0]], [[1, 0]]], 0.5, 1)
Output: None
Hints
Hint 1
Process steps in increasing order and stop at the first step where any pair overlaps; no earlier step can be wrong then.
Hint 2
Check for overlaps before applying the update for that step. This covers step 0 and the final state without ever reading a command at index steps.
Hint 3
Compare dx*dx + dy*dy against (r_i + r_j)**2 using <= to avoid sqrt and to count exact contact.
Hint 4
Build each pair as (min(id_a, id_b), max(id_a, id_b)) using ids rather than list indices, then sort the collected pairs before returning.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a direct simulation. For each step from 0 to steps inclusive:
- Test every unordered pair of robots for overlap in the current state.
- If at least one pair overlaps, return the current step together with all overlapping pairs, each ordered by id and the whole list sorted.
- Otherwise, if
step < steps, advance every robot by one forward Euler step using its command for that step.
Checking before updating handles the initial state naturally, and also checks the state after the last command without reading a command at index steps, which does not exist.
Why it is correct
- Earliest step: steps are visited in increasing order and we return at the first one with any overlap, so no earlier step can contain an overlap.
- All pairs at that step: at the returning step we scan every pair
i < j, so each unordered pair is considered exactly once and a robot is never compared with itself. - Ordering: each pair is stored as
(min(id), max(id)), which is independent of list positions, and the list is then sorted lexicographically. - Dynamics: each robot's new state depends only on its own old state and its own command. The old heading is used for the position update, as forward Euler requires. Since robots do not interact in the dynamics, updating them one at a time is safe.
- Touching counts:
dx^2 + dy^2 <= (r_i + r_j)^2is equivalent todist <= r_i + r_jbecause both sides are non-negative, so exact contact is detected without a square root.
Complexity
With N robots and S = steps:
- Time:
O(S * N^2), since each of theS + 1steps doesO(N^2)pair checks andO(N)updates. Sorting happens once and costs at mostO(N^2 log N). - Space:
O(N)for the states, plus up toO(N^2)for the pair list in the worst case.
Reference solution
import math
from typing import Dict, List, Optional
def find_first_collision(agents: List[Dict], controls: List[List[List[float]]], dt: float, steps: int) -> Optional[List]:
n = len(agents)
states = [[a["x"], a["y"], a["theta"]] for a in agents]
radii = [a["radius"] for a in agents]
ids = [a["id"] for a in agents]
for step in range(steps + 1):
collisions = []
for i in range(n):
for j in range(i + 1, n):
dx = states[i][0] - states[j][0]
dy = states[i][1] - states[j][1]
r = radii[i] + radii[j]
if dx * dx + dy * dy <= r * r:
collisions.append((min(ids[i], ids[j]), max(ids[i], ids[j])))
if collisions:
return [step, [list(p) for p in sorted(collisions)]]
if step < steps:
for i in range(n):
v, omega = controls[i][step]
x, y, theta = states[i]
states[i] = [
x + v * math.cos(theta) * dt,
y + v * math.sin(theta) * dt,
theta + omega * dt,
]
return None