← Questions
Match couriers to orders on a line within a distance limit
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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 andDare 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 < c2and ordero1 < o2, pairingc1-o1andc2-o2is never worse in total distance and stays withinD. - A dynamic program over the two sorted lists:
dp[i][j]is the best(count, -distance)for the firsticouriers andjorders, choosing to skip a courier, skip an order, or pair them when they are withinD. 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
corders. - The points are in two dimensions: what changes?
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
