KatInterview

Distance-to-Go Along Batched 2D Routes

Arrays & HashingModel answer
MediumModel answerArrays & Hashingsuffix-sumnumpyvectorization

Last updated

Given a batch of 2D routes, compute for each waypoint the length of the remaining route to the final waypoint, in linear time, handling short and empty inputs.

Distance-to-Go Along Batched 2D Routes

A planner produces several routes at once. Each route is an ordered list of 2D waypoints. For every waypoint you want to know how far remains to travel along the route before reaching its final waypoint.

Input

  • points: a nested array of shape [B, N, 2].
    • points[b][i] = (x, y) is the i-th waypoint of route b.

Output

  • rem: an array of shape [B, N].
    • rem[b][i] is the total straight-line length of all consecutive segments from waypoint i through waypoint N-1.

Formally:

rem[b][i] = sum over j = i .. N-2 of dist(points[b][j], points[b][j+1])
rem[b][N-1] = 0

where dist is the Euclidean distance.

Example

For one route [(0,0), (3,4), (3,10)], the segment lengths are 5 and 6, so rem = [11, 6, 0].

Requirements

  • Run in O(B·N) time.
  • Handle N = 1 correctly (every output is 0).
  • Briefly discuss other edge cases you would guard against.

What to deliver

  1. A straightforward implementation (plain Python loops is fine).
  2. A vectorized implementation (NumPy or PyTorch) with no Python-level loops over waypoints.
  3. A short justification of correctness and complexity.
  4. A note on numerical-precision pitfalls and how you would handle routes of different lengths in one batch.

Hints

Hint 1

Look at two neighbouring answers: rem[i] and rem[i+1] differ by exactly one segment. Can you build the answers from the end of the route?

Hint 2

For the vectorized form, first compute all N-1 segment lengths, then think about how to turn a prefix sum (cumsum) into a suffix sum. Pay attention to where the N-1 values go in an array of N slots.

Hint 3

Avoid computing total minus prefix: subtracting two large, nearly equal floats can give tiny negative values. Also consider what happens for N = 0 or N = 1, and for padded routes of different lengths.