Compute suffix sums over waypoints
Company: Tesla
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to compute geometric suffix sums over batched 2D trajectories, testing skills in array manipulation, Euclidean distance computation, and runtime-conscious algorithm design within the Coding & Algorithms domain.
Constraints
- 0 <= B
- Each trajectory contains N waypoints, where N >= 1 in the standard case
- Each waypoint has exactly 2 coordinates
- The algorithm should run in O(B·N) time
Examples
Input: ([[(0, 0), (3, 4), (6, 8)]],)
Expected Output: [[10.0, 5.0, 0.0]]
Explanation: The segment lengths are 5 and 5, so the remaining distances are [10, 5, 0].
Input: ([[(0, 0), (0, 3), (4, 3), (4, 0)], [(1, 1), (4, 5), (7, 9), (7, 9)]],)
Expected Output: [[10.0, 7.0, 3.0, 0.0], [10.0, 5.0, 0.0, 0.0]]
Explanation: First trajectory has segment lengths 3, 4, 3. Second has 5, 5, 0 because the last two points are identical.
Input: ([[(2, -1)]],)
Expected Output: [[0.0]]
Explanation: A trajectory with one waypoint has no remaining path, so the only value is 0.
Input: ([],)
Expected Output: []
Explanation: An empty batch produces an empty result.
Input: ([[(-1, -1), (-1, 2), (3, 2), (3, 2)]],)
Expected Output: [[7.0, 4.0, 0.0, 0.0]]
Explanation: The segment lengths are 3, 4, and 0, so the suffix sums are [7, 4, 0, 0].
Solution
def solution(points):
import math
result = []
for traj in points:
n = len(traj)
if n == 0:
result.append([])
continue
rem = [0.0] * n
running = 0.0
for i in range(n - 2, -1, -1):
x1, y1 = traj[i]
x2, y2 = traj[i + 1]
running += math.hypot(x2 - x1, y2 - y1)
rem[i] = running
result.append(rem)
return result
Time complexity: O(B·N). Space complexity: O(B·N) for the returned array.
Hints
- For one trajectory, try processing waypoints from right to left instead of recomputing the remaining distance from scratch for every index.
- Keep a running suffix total of segment lengths and update it as you move backward.