KatInterview

Verify Safe Spacing During Multi-Vehicle Forward Simulation

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingsimulationphysicsiteration

Last 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 meters
  • v: 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.0 seconds
  • 0.001 ≤ dt ≤ 1.0 seconds
  • min_distance ≥ 0.0 meters
  • time_headway ≥ 0.0 seconds
  • Initial velocities v ≥ 0.0 m/s
  • Vehicle lengths length > 0.0 meters
  • -10.0 ≤ a ≤ 10.0 m/s²
  • Either front_vehicle or rear_vehicle (or both) may be None

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