KatInterview

Calculate Emergency Braking Distance and Decision

Math & Bit ManipulationAuto-graded · 18 test cases
MediumAuto-gradedMath & Bit Manipulationphysicskinematicsnumerical-reasoning

Last updated

Tests understanding of kinematic equations, motion physics, and numerical reasoning to determine whether a vehicle can stop in time given speed, obstacle distance, deceleration, and reaction delay.

You are building a collision avoidance system for a vehicle. Your task is to determine whether the vehicle can safely stop before reaching an obstacle.

Write a function that takes the following parameters:

  • v: current velocity in meters per second (m/s)
  • d: distance to the obstacle in meters (m)
  • a_max: maximum deceleration rate in meters per second squared (m/s²)
  • t_r: reaction time in seconds (s) — the delay before brakes engage

During the reaction time, the vehicle continues at constant velocity v. After the reaction time elapses, the vehicle decelerates uniformly at rate a_max until it comes to a complete stop.

Your function must return a dictionary with three keys:

  • "should_brake": a boolean indicating whether the vehicle can stop before reaching the obstacle (stopping distance ≤ obstacle distance)
  • "braking_start_time": the reaction time t_r if braking is possible, otherwise None
  • "stopping_distance": the total distance traveled from now until the vehicle stops (includes both reaction distance and braking distance)

The stopping distance consists of two components:

  1. Reaction distance: distance traveled at constant velocity during reaction time = v × t_r
  2. Braking distance: distance traveled while decelerating to a stop = v² / (2 × a_max)

Total stopping distance = reaction distance + braking distance

Constraints

  • 0 ≤ v ≤ 100 (velocity in m/s)
  • 0 ≤ d ≤ 1000 (distance in meters)
  • 0 < a_max ≤ 20 (deceleration in m/s²)
  • 0 ≤ t_r ≤ 5 (reaction time in seconds)
  • All inputs are valid numbers
  • Return float('inf') for stopping distance if a_max is 0 or negative

Examples

Example 1

Input: calculate_braking(20, 100, 8, 1)

Output: {'should_brake': True, 'braking_start_time': 1, 'stopping_distance': 45}

Example 2

Input: calculate_braking(20, 40, 8, 1)

Output: {'should_brake': False, 'braking_start_time': None, 'stopping_distance': 45}

Example 3

Input: calculate_braking(10, 30, 5, 0.5)

Output: {'should_brake': True, 'braking_start_time': 0.5, 'stopping_distance': 15}

Hints

Hint 1

The vehicle travels in two phases: constant velocity during reaction time, then uniform deceleration until stopped.

Hint 2

Use the kinematic equation for constant acceleration: the distance to stop from velocity v with deceleration a is v²/(2a).

Hint 3

Compare the total stopping distance (reaction distance plus braking distance) against the obstacle distance to decide if braking will succeed.