Verify Safe Spacing During Multi-Vehicle Forward Simulation
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests discrete-time physics simulation with kinematic updates and safety constraint checking across multiple moving objects.
You are building a collision avoidance system that must verify whether sufficient spacing is maintained between vehicles over a time period.
Given a primary vehicle (ego) and up to two nearby vehicles (front and rear), simulate their motion forward in time and check that minimum separation distances are preserved at every time step.
Vehicle Representation
Each vehicle is represented as a dictionary with these keys:
s: position of the front bumper in metersv: current velocity in m/s (non-negative)a: constant acceleration in m/s²length: vehicle length in meters (positive)
Motion Physics
At each simulation step of duration step_time, update each vehicle's state:
If the vehicle would stop or reverse (v + a * step_time ≤ 0 and a < 0):
- Travel the exact stopping distance:
distance = -v² / (2 * a) - Set new position:
s_new = s + distance - Set velocity to
0.0 - Set acceleration to
0.0
Otherwise (normal motion):
- Update position:
s_new = s + v * step_time + 0.5 * a * step_time² - Update velocity:
v_new = v + a * step_time
Safety Requirements
At every checked time point t = 0, dt, 2·dt, ..., T (where T is the horizon):
If a front vehicle exists, the gap between ego's front bumper and the front vehicle's rear bumper must satisfy:
gap_front = front.s - front.length - ego.s
gap_front ≥ min_distance + ego.v * time_headway
If a rear vehicle exists, the gap between the rear vehicle's front bumper and ego's rear bumper must satisfy:
gap_rear = ego.s - ego.length - rear.s
gap_rear ≥ min_distance + rear.v * time_headway
Return True if all safety requirements are met at every time step up to and including the horizon. Return False if any constraint is violated at any checked time.
Constraints
0.0 ≤ horizon ≤ 10.0seconds0.001 ≤ dt ≤ 1.0secondsmin_distance ≥ 0.0meterstime_headway ≥ 0.0seconds- Initial velocities
v ≥ 0.0m/s - Vehicle lengths
length > 0.0meters -10.0 ≤ a ≤ 10.0m/s²- Either
front_vehicleorrear_vehicle(or both) may beNone
Examples
Example 1
Input: verify_safe_spacing({'s': 50, 'v': 20, 'a': 0, 'length': 4.5}, {'s': 80, 'v': 20, 'a': 0, 'length': 4.5}, {'s': 20, 'v': 20, 'a': 0, 'length': 4.5}, 2, 1, 2, 1)
Output: True
Example 2
Input: verify_safe_spacing({'s': 50, 'v': 20, 'a': -5, 'length': 5}, None, {'s': 30, 'v': 25, 'a': 0, 'length': 5}, 2, 0.5, 3, 1)
Output: False
Hints
Hint 1
Check safety at time zero before simulating any motion
Hint 2
Handle the special case where a decelerating vehicle comes to a complete stop during a time step
Hint 3
Take the minimum of dt and the remaining time to ensure you land exactly on the horizon
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simulating the forward motion of multiple vehicles using discrete time steps and verifying safety constraints at each point in time.
The solution follows these steps:
- Copy the input vehicles to avoid mutating the caller's data
- Check initial safety at time zero before any motion occurs
- Simulate in time steps: for each step until the horizon is reached:
- Determine the step size (minimum of
dtand remaining time) - Update each vehicle's position and velocity using kinematic equations
- Check safety constraints after the update
- Determine the step size (minimum of
- Return early on the first constraint violation, or return
Trueif all checks pass
Kinematic Update Logic
For each vehicle at each time step:
- If the vehicle is decelerating and would reach zero velocity (
v + a·step ≤ 0witha < 0), compute the exact stopping distance usingd = -v²/(2a), then set velocity and acceleration to zero to prevent backward motion - Otherwise, apply standard constant-acceleration kinematics: update position by
v·step + 0.5·a·step²and velocity bya·step
Safety Check Logic
At each time point, verify:
- Front constraint: If a front vehicle exists, the gap
front.s - front.length - ego.smust be at leastmin_distance + ego.v * time_headway. Note that ego's velocity determines the required headway since ego is the follower. - Rear constraint: If a rear vehicle exists, the gap
ego.s - ego.length - rear.smust be at leastmin_distance + rear.v * time_headway. The rear vehicle's velocity determines the headway since it is the follower.
A gap exactly equal to the requirement is considered safe (not a violation).
Why This Works
The problem defines safety as holding at the discrete sample points 0, dt, 2dt, ..., T. The simulation advances all vehicles synchronously and checks constraints at exactly these times. The stopping logic prevents unphysical negative velocities, matching the specified kinematic model. Early termination on the first failure is correct since a single violation makes the entire maneuver unsafe.
Complexity
- Time: O(horizon / dt) — each time step performs constant work for up to three vehicles
- Space: O(1) — only shallow copies of the input dictionaries are stored
Solution
from typing import Dict, Optional
def verify_safe_spacing(ego: Dict[str, float], front_vehicle: Optional[Dict[str, float]], rear_vehicle: Optional[Dict[str, float]], horizon: float, dt: float, min_distance: float, time_headway: float) -> bool:
def duplicate_vehicle(vehicle):
return None if vehicle is None else dict(vehicle)
ego = duplicate_vehicle(ego)
front = duplicate_vehicle(front_vehicle)
rear = duplicate_vehicle(rear_vehicle)
def check_spacing():
if front is not None:
gap = front['s'] - front['length'] - ego['s']
if gap < min_distance + ego['v'] * time_headway:
return False
if rear is not None:
gap = ego['s'] - ego['length'] - rear['s']
if gap < min_distance + rear['v'] * time_headway:
return False
return True
def update_vehicle(vehicle, step):
if vehicle is None:
return
s, v, a = vehicle['s'], vehicle['v'], vehicle['a']
if v + a * step <= 0 and a < 0:
vehicle['s'] = s - v * v / (2 * a)
vehicle['v'] = 0.0
vehicle['a'] = 0.0
else:
vehicle['s'] = s + v * step + 0.5 * a * step * step
vehicle['v'] = v + a * step
if not check_spacing():
return False
time_elapsed = 0.0
while time_elapsed < horizon:
step = min(dt, horizon - time_elapsed)
update_vehicle(ego, step)
update_vehicle(front, step)
update_vehicle(rear, step)
time_elapsed += step
if not check_spacing():
return False
return True