Distance-to-Go Along Batched 2D Routes
Arrays & HashingModel answerLast 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 routeb.
Output
rem: an array of shape[B, N].rem[b][i]is the total straight-line length of all consecutive segments from waypointithrough waypointN-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 = 1correctly (every output is0). - Briefly discuss other edge cases you would guard against.
What to deliver
- A straightforward implementation (plain Python loops is fine).
- A vectorized implementation (NumPy or PyTorch) with no Python-level loops over waypoints.
- A short justification of correctness and complexity.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Computing each rem[b][i] independently by summing its whole suffix costs O(N) per entry, so O(B·N²) overall. That is unnecessary because neighbouring suffixes share nearly all of their terms:
seg[b][i] = ||points[b][i+1] - points[b][i]||
rem[b][i] = seg[b][i] + rem[b][i+1]
rem[b][N-1] = 0
So we walk each route backwards from the final waypoint, keeping a running total. Each segment length is computed once and each output written once. This is a prefix sum in the reverse direction.
Why it is correct
Induction from the end of the route:
- Base:
rem[N-1] = 0, an empty sum, which also matches the definition. - Step: if
rem[i+1]equals the sum ofseg[j]forj = i+1..N-2, thenseg[i] + rem[i+1]equals the sum forj = i..N-2, which is the definition ofrem[i].
Routes in the batch are independent, so the recurrence applies per route.
Complexity
- Time:
O(B·N): N-1 distance computations and N-1 additions per route, eachO(1). - Space:
O(B·N)for the output. The loop version needs only one scalar of extra state per route. The vectorized version allocates anO(B·N)temporary for segment lengths.
Plain Python
import math
def distance_to_go(points):
out = []
for route in points:
n = len(route)
row = [0.0] * n
running = 0.0
for i in range(n - 2, -1, -1):
x0, y0 = route[i]
x1, y1 = route[i + 1]
running += math.hypot(x1 - x0, y1 - y0)
row[i] = running
out.append(row)
return out
When n is 0 or 1 the loop does not execute, so we return [] or [0.0] with no index error.
Vectorized (NumPy)
import numpy as np
def distance_to_go_np(points):
pts = np.asarray(points, dtype=np.float64)
B, N, _ = pts.shape
rem = np.zeros((B, N), dtype=pts.dtype)
if N <= 1:
return rem
seg = np.linalg.norm(np.diff(pts, axis=1), axis=-1) # [B, N-1]
rem[:, :-1] = np.cumsum(seg[:, ::-1], axis=1)[:, ::-1] # suffix sums
return rem
Step by step:
np.diff(..., axis=1)gives displacement vectors, shape[B, N-1, 2].norm(..., axis=-1)gives segment lengths, shape[B, N-1].- Flip,
cumsum, flip again converts a prefix sum into a suffix sum. Without the double flip you get prefix sums, which is a common bug. - Writing into
rem[:, :-1]places the N-1 values in the first N-1 slots and leaves the last column at 0, avoiding an off-by-one.
In PyTorch the same idea is seg.flip(-1).cumsum(-1).flip(-1), which is also differentiable.
Worked check
Route [(0,0), (3,4), (3,10)] gives segments [5, 6], so rem = [11, 6, 0].
Edge cases
- N = 1: no segments, output is all zeros.
- N = 0: return an empty row per route and never touch index
N-1. Not stated in the problem, but worth guarding. - B = 0: return an empty result (shape
(0, N)). - Duplicate consecutive waypoints: segment length 0, so
remstays flat. No special handling. - Sanity properties: each row is non-negative and non-increasing, and
rem[b][0]equals the total route length. These are good test assertions.
Numerical considerations
- Do not compute
total - prefix[i]. Near the end of a long route this subtracts two large, almost equal floats, and catastrophic cancellation can yield small negative values. Accumulating from the end starts with small numbers and stays non-negative. hypotavoids intermediate overflow or underflow compared withsqrt(dx*dx + dy*dy). It rarely matters for realistic coordinates but is a cheap improvement.- For very long routes, float32 accumulation can drift; use float64 or compensated summation if precision matters.
Common mistakes
- Using the nested-sum
O(B·N²)approach. - Forgetting the double flip and returning prefix sums.
- Producing an array of length N-1 instead of N, or shifting values by one index.
- Crashing on
N = 1by indexing an empty segment array.
Follow-ups
- Variable-length routes with padding: build a mask of valid segments (segment
iis valid ifi + 1 < length[b]), multiply segment lengths by the mask before the reversed cumsum, and optionally mask the output beyondlength[b]. Because padded segments contribute 0, valid entries are unaffected. - Find where a given distance remains: since
rem[b]is non-increasing, binary search finds the first waypoint withrem <= dinO(log N)per route. - 3D or higher dimensions: only the norm axis changes; the recurrence is identical.
- Arc-length parameterization:
total - rem(computed once for display, not as the primary method) gives distance travelled so far, and dividing by the total gives a normalized progress feature.