← Questions

Match couriers to orders on a line within a distance limit

0
GoogleCodingLast asked Dec 2025

Couriers and delivery orders are points on a number line. Each courier can take at most one order and each order needs at most one courier, and a courier can take an order only if they are within distance D of each other. First maximize the number of orders delivered; among all ways to deliver that many, minimize the total distance travelled.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • best_assignment(couriers: list[int], orders: list[int], D: int) -> tuple[int, int] — returns (deliveries, total_distance).

Example

couriers = [1, 6, 10], orders = [2, 5, 11, 20], D = 2   ->  (3, 3)   # 1-2, 6-5, 10-11; 20 is out of reach
couriers = [0, 4],     orders = [2],            D = 2   ->  (1, 2)   # either courier, distance 2
couriers = [],         orders = [1],            D = 3   ->  (0, 0)

Constraints

  • Up to a few thousand couriers and orders; positions can repeat.
  • D >= 0; positions and D are integers.

Clarifying questions

  • Must every courier deliver, or only as many as possible?
  • Is the objective lexicographic: count first, then distance?
  • Can several couriers or orders share a position?
  • What should empty inputs return?

What a strong answer covers

  • Sorting both lists, and the exchange argument that some optimal matching never crosses: if courier c1 < c2 and order o1 < o2, pairing c1-o1 and c2-o2 is never worse in total distance and stays within D.
  • A dynamic program over the two sorted lists: dp[i][j] is the best (count, -distance) for the first i couriers and j orders, choosing to skip a courier, skip an order, or pair them when they are within D. Comparing pairs of values gives the lexicographic objective. O(n · m) time, O(m) memory with rolling rows.
  • Why a greedy "nearest available" choice can fail on either objective.
  • Tests against a brute force on small random inputs, duplicates and empty lists.

Follow-ups

  • Only the count matters: a two-pointer greedy in O((n + m) log(n + m)).
  • Each courier can carry up to c orders.
  • The points are in two dimensions: what changes?
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding