Compute Speeding Penalties from Trajectory Data
Arrays & HashingAuto-graded · 17 test casesLast 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:
- Duration of violations: the total time (in seconds) during which the instantaneous velocity exceeded the threshold
- 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
iandi+1is 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) ≤ 10000 ≤ len(trajectory) ≤ 500for each trajectory-10000 ≤ x, y ≤ 100000 < 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires measuring two aspects of velocity threshold violations: how long violations last and how severe they are.
For each trajectory, we iterate through consecutive position pairs to reconstruct the instantaneous velocity at each interval. Since positions are sampled at 10 Hz, the time step is 0.1 seconds. Velocity is the Euclidean distance between consecutive points divided by this time step.
For each interval where velocity strictly exceeds the limit:
- Increment a counter (for the duration metric)
- Accumulate the product of excess velocity and time step (for the magnitude metric)
The duration metric converts the count to seconds by multiplying by 0.1. The magnitude metric naturally accumulates in units of distance (meters), representing how much "extra distance" was traveled above the allowed rate.
Trajectories with fewer than two points have no intervals to measure, so both metrics are zero.
Correctness
The velocity calculation uses the standard Euclidean distance formula and the known sampling rate. The strict inequality ensures that driving exactly at the limit is not penalized. Both metrics are additive over intervals, so linear accumulation correctly aggregates the measurements. Edge cases (empty or single-point paths) are handled by the loop bounds.
Complexity
- Time: O(N × M) where N is the number of trajectories and M is the average number of waypoints per trajectory. Each interval requires constant-time distance and comparison operations.
- Space: O(N) for the output lists. The computation uses constant auxiliary space per trajectory.
Implementation
from math import hypot
from typing import Dict, List
def compute_speeding_metrics(trajectories: List[List[List[float]]], velocity_limit: float) -> Dict[str, List[float]]:
time_speeding = []
excess_speed_integral = []
dt = 0.1 # sampling interval in seconds
for path in trajectories:
num_intervals = len(path) - 1
violation_count = 0
excess_accumulator = 0.0
for i in range(num_intervals):
dx = path[i + 1][0] - path[i][0]
dy = path[i + 1][1] - path[i][1]
velocity = hypot(dx, dy) / dt
excess = max(0.0, velocity - velocity_limit)
if excess > 0.0:
violation_count += 1
excess_accumulator += excess * dt
time_speeding.append(violation_count * dt)
excess_speed_integral.append(excess_accumulator)
return {
"time_speeding_seconds": time_speeding,
"excess_speed_integral": excess_speed_integral,
}