Implement automatic braking logic in Python
Company: Tesla
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of kinematics, motion modeling, and numerical reasoning for safety-critical control logic, focusing on stopping-distance computation and the impact of reaction time on braking decisions.
Constraints
- 0 <= v <= 10^4
- 0 <= d <= 10^7
- a_max > 0
- 0 <= t_r <= 10^3
Examples
Input: (20, 100, 5, 1)
Expected Output: ('WAIT', 1.0, 60.0)
Explanation: Braking distance is 20^2 / (2*5) = 40. During the 1-second delay, the car travels 20 more meters. Total stopping distance is 60, which is within 100, so waiting is safe.
Input: (20, 50, 5, 1)
Expected Output: ('BRAKE_NOW', 0.0, 40.0)
Explanation: Immediate braking needs 40 meters, but waiting 1 second would require 60 meters total. Since 60 > 50, the car must brake now.
Input: (20, 30, 5, 1)
Expected Output: ('BRAKE_NOW', 0.0, 40.0)
Explanation: Even immediate braking needs 40 meters, which is more than the 30-meter gap. The safest decision is still to brake now.
Input: (12, 30, 6, 1.5)
Expected Output: ('WAIT', 1.5, 30.0)
Explanation: Braking distance is 12^2 / (2*6) = 12. Reaction distance is 12 * 1.5 = 18. Total stopping distance is exactly 30, so waiting is still safe.
Input: (10, 10, 5, 1)
Expected Output: ('BRAKE_NOW', 0.0, 10.0)
Explanation: Immediate braking distance is exactly 10 meters, but waiting 1 second would make the total stopping distance 20 meters. So braking must start immediately.
Solution
def solution(v, d, a_max, t_r):
if a_max <= 0:
raise ValueError('a_max must be positive')
braking_distance = (v * v) / (2.0 * a_max)
delayed_stopping_distance = (v * t_r) + braking_distance
if delayed_stopping_distance > d:
return ('BRAKE_NOW', 0.0, braking_distance)
else:
return ('WAIT', float(t_r), delayed_stopping_distance)
Time complexity: O(1). Space complexity: O(1).
Hints
- First compute the braking distance if the car starts braking right now: v^2 / (2 * a_max).
- Then compare the total stopping distance after waiting t_r seconds, v * t_r + braking_distance, against d.