← Questions
Best locker location on a grid with obstacles
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's coding round, last asked Aug 2025. It tests bfs and grids.
Houses and trees sit on cells of an integer grid. Choose a cell for a locker that is not a tree cell and minimizes the total Manhattan distance from the locker to every house. Return that minimal total. Distances are measured as |x1 - x2| + |y1 - y2|; trees only block placement, not walking.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
best_locker(houses: list[tuple[int, int]], trees: list[tuple[int, int]]) -> tuple[int, tuple[int, int]]— returns the minimal total distance and one optimal cell. With no houses, return(0, any non-tree cell).
Example
best_locker([(0, 0), (0, 4), (2, 2)], []) -> (6, (0, 2)) # the median cell
best_locker([(0, 0), (0, 4), (2, 2)], [(0, 2)]) -> (7, (0, 1)) # (0, 3) and (1, 2) also cost 7
Constraints
-
0 <= len(houses), len(trees) <= 10^4; coordinates are in[-10^6, 10^6]. - A house and a tree may share a cell; the locker still cannot go there.
Clarifying questions
- Do trees block walking, or only where the locker can stand?
- Can the locker share a cell with a house?
- Must the locker stay inside the bounding box of the houses?
- If several cells tie, which one should be returned?
What a strong answer covers
- Manhattan distance separates into an x part and a y part, each minimized at a median; the unconstrained optimum is
(median x, median y). - When that cell is a tree: the cost is convex in each axis, so search outward from the median in increasing order of cost (a small best-first search over neighbouring cells) until a non-tree cell is found; at most
len(trees) + 1cells need checking. - Computing the cost of a candidate in O(log n) with sorted coordinates and prefix sums, instead of O(n).
- Edge cases: no houses, an even number of houses (a whole range of medians), every median cell blocked.
Follow-ups
- Trees also block walking: now distances come from a breadth-first search on a bounded grid (one multi-source BFS per house, or a BFS from each candidate).
- Place two lockers; each house uses the nearer one.
- Minimize the maximum distance instead of the sum.
Where it's asked
- Amazon · Coding · Last asked Aug 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
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
