KatInterview

Compute Speeding Penalties from Trajectory Data

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarrayssimulationnumerical-methods

Last updated

Measures violations of a velocity threshold by calculating duration and magnitude of excess speed from sampled position sequences.

You are analyzing recorded vehicle paths to measure compliance with a velocity threshold. Each path is represented as a sequence of 2D positions sampled at a fixed frequency.

Given a batch of trajectories and a velocity threshold, compute two metrics for each trajectory:

  1. Duration of violations: the total time (in seconds) during which the instantaneous velocity exceeded the threshold
  2. Magnitude of violations: the integral of excess velocity over time (the area between the actual velocity curve and the threshold, where velocity exceeds the threshold)

Input

  • trajectories: a list of paths, where each path is a list of [x, y] coordinate pairs (floats)
  • velocity_limit: a positive float representing the maximum allowed speed

Output

A dictionary with two keys:

  • "time_speeding_seconds": a list of floats, one per trajectory, measuring the total duration of threshold violations
  • "excess_speed_integral": a list of floats, one per trajectory, measuring the cumulative magnitude of violations

Details

  • Positions are sampled at 10 Hz, so consecutive waypoints are separated by 0.1 seconds
  • Velocity between waypoints i and i+1 is computed as the Euclidean distance divided by 0.1
  • A violation occurs when velocity strictly exceeds the limit (equality is not a violation)
  • For trajectories with fewer than 2 waypoints, both metrics should be 0.0
  • Coordinates are in consistent metric units (meters); velocities are in meters per second

Constraints

  • 1 ≤ len(trajectories) ≤ 1000
  • 0 ≤ len(trajectory) ≤ 500 for each trajectory
  • -10000 ≤ x, y ≤ 10000
  • 0 < velocity_limit ≤ 100

Examples

Example 1

Input: compute_speeding_metrics([[[0, 0], [1, 0], [2.5, 0], [3, 0]], [[0, 0], [0.5, 0], [1, 0]]], 10)

Output: {'time_speeding_seconds': [0.1, 0], 'excess_speed_integral': [0.5, 0]}

Hints

Hint 1

Calculate instantaneous velocity from each pair of consecutive positions using the Euclidean distance formula and the 0.1 second interval.

Hint 2

The duration metric counts how many intervals have violations, then multiplies by 0.1 to convert to seconds.

Hint 3

The magnitude metric sums the product of excess velocity and interval duration across all violations.