Greedy Robot-to-Item Dispatch Across an Obstacle Grid
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Inside an m x n warehouse grid, k robots must be dispatched to collect k stationary packages (1 package per robot). Each cell grid[r][c] equals 0 when passable or 1 when blocked by a wall. Coordinates robots[i] = [r, c] and items[j] = [r, c] specify the starting row and column of robot i and package j.
Robots step one cell at a time in the four cardinal directions (north, south, east, west), staying inside grid boundaries and avoiding 1 cells. The travel distance between robot i and package j is the fewest steps needed to walk from robots[i] to items[j].
Dispatching runs in k sequential rounds:
- Out of every pair
(i, j)where robotiand packagejare both still unmatched, select the pair with the minimum travel distance. - Break distance ties by choosing the smallest robot index
i, and break any remaining tie by choosing the smallest package indexj. - Permanently match robot
iwith packagejso neither participates in subsequent rounds.
Return an integer list assigned of length k where assigned[i] gives the package index matched to robot i.
def assign_robots(grid: list[list[int]], robots: list[list[int]], items: list[list[int]]) -> list[int]:
Examples
Example 1
Input:
grid = [
[0, 0, 0, 0],
[0, 0, 0, 0]
]
robots = [[0, 0], [0, 3], [1, 1]]
items = [[0, 2], [1, 3], [1, 0]]
Output: [2, 0, 1]
Explanation: Four (robot, item) pairs sit 1 step apart: (0, 2), (1, 0), (1, 1), and (2, 2). Round 1 picks (0, 2) via smallest robot index (0), claiming package 2. Round 2 compares the remaining 1-step pairs (1, 0) and (1, 1) (since package 2 is gone) and picks (1, 0) via smallest package index (0). Round 3 matches robot 2 with package 1 (2 steps away).
Example 2
Input:
grid = [
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 0]
]
robots = [[0, 0], [1, 3]]
items = [[0, 2], [2, 0]]
Output: [1, 0]
Explanation: Column 1 blocks rows 0 and 1, forcing robot 0 around row 2 to reach package 0 in 6 steps, whereas package 1 is 2 steps south. Robot 1 reaches package 0 in 2 steps and package 1 in 4 steps. Between the 2-step pairs (0, 1) and (1, 0), robot 0 wins the tie and takes package 1, leaving package 0 for robot 1.
Example 3
Input:
grid = [[0, 0, 0]]
robots = [[0, 2], [0, 0]]
items = [[0, 1], [0, 0]]
Output: [0, 1]
Explanation: Robot 1 already stands on package 1 (0 steps), so (1, 1) wins Round 1 ahead of robot 0 despite having a larger robot index. Robot 0 then takes package 0 (1 step).
Constraints
1 <= m, n <= 50wherem = len(grid)andn = len(grid[0])(all rows have lengthn).- Every
grid[r][c]is either0(passable) or1(wall). 1 <= k <= 50withlen(robots) == len(items) == k.- All robot and package positions lie on passable cells (
grid[r][c] == 0) within bounds. - Robot coordinates are mutually distinct, and package coordinates are mutually distinct; a robot and a package may occupy the same cell (
0steps). - Every package is reachable from every robot along passable cells.
Step-by-step walkthrough
Understand the two subproblems: obstacle distances and greedy rounds
We have an
m x nwarehouse of passable cells (0) and walls (1),krobots, andkpackages. We need to returnassigned_itemof lengthkwhereassigned_item[i]records the package index matched to roboti.Solving this cleanly means separating two distinct tasks:
- True shortest-path distance around walls: Robots step north, south, east, or west across passable cells (
0s). When walls (1s) block the direct route, the real step count can exceed straight-line distanceabs(r1 - r2) + abs(c1 - c2). - Global greedy matching with deterministic tie-breakers: In each round, across all remaining
(robot, item)pairs, we pick the single pair minimizing:steps(shortest walking distance),- then
robot_idx(smallest robot indexiwhen distances tie), - then
item_idx(smallest package indexjif still tied).
Example 2 grid (# = wall): col: 0 1 2 3 row 0: R0 # I0 . R0 at (0,0) reaches I1 at (2,0) in 2 steps south, row 1: . # . R1 whereas the wall in col 1 forces a 6-step detour row 2: I1 . . . along row 2 to reach I0 at (0,2)!- True shortest-path distance around walls: Robots step north, south, east, or west across passable cells (
Why per-pair searches and repeated round scans waste work
A literal brute-force implementation would: - run a separate shortest-path search for every
(robot_i, item_j)pair (k * ksearches over up tom * ncells), and - runkseparate rounds, rescanning allk * kpairs every round (k^3comparisons).Notice the wasted work in step 1: all
ksearches starting fromrobot_0explore the exact same grid from the exact same cell! Running one search per robot computes the shortest distance to every cell — and therefore to allkpackages — in a single pass.Phase 1: Find shortest paths around walls with one BFS per robot
Because every move costs
1step, Breadth-First Search (BFS) — expanding cells wave by wave using a first-in, first-out queue (collections.deque) — visits cells at0steps, then1step, then2steps, and so on. The first time BFS reaches any passable cell is guaranteed to be along a shortest path.We allocate a 2D table
distfilled with-1. That-1acts both as an "unvisited" marker during the search and as an "unreachable / wall" marker afterward.BFS distance waves from R0 at (0,0) on Example 2: 0 # 6 7 1 # 5 6 2 3 4 5 --> dist[0][2] = 6 (to I0), dist[2][0] = 2 (to I1)from collections import deque def _bfs_distances(grid: list[list[int]], start: list[int]) -> list[list[int]]: """Return a grid of shortest 4-directional step counts from `start` (-1 if unreachable).""" num_rows = len(grid) num_cols = len(grid[0]) start_row, start_col = start # dist[r][c]: fewest steps from `start` to (r, c), or -1 if not yet reached / blocked. dist = [[-1] * num_cols for _ in range(num_rows)] dist[start_row][start_col] = 0 # queue: FIFO deque of (row, col) cells expanding outward wave by wave (0 steps, 1 step, ...). queue = deque([(start_row, start_col)]) directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] while queue: row, col = queue.popleft() for d_row, d_col in directions: next_row = row + d_row next_col = col + d_col # Because every move costs 1 step, the first time BFS reaches a free cell (`dist == -1`) # is guaranteed to be via a shortest path; setting `dist` immediately avoids re-queuing. if ( 0 <= next_row < num_rows and 0 <= next_col < num_cols and grid[next_row][next_col] == 0 and dist[next_row][next_col] == -1 ): dist[next_row][next_col] = dist[row][col] + 1 queue.append((next_row, next_col)) return distPhase 2: Turn `k` greedy rounds into one sorted pass
After calling
_bfs_distancesonce per robot, we pack every reachable pair into a 3-tuple:(steps, robot_idx, item_idx)When Python sorts tuples, it compares element
0first (steps), breaks ties with element1(robot_idx), and breaks remaining ties with element2(item_idx). That matches the dispatch tie-breakers automatically!Why does scanning the sorted list once produce the exact same matches as
kseparate rounds? - Round 1 chooses the smallest tuple overall — index0of our sorted list. - Any later round chooses the smallest tuple whose robot and package are both still unmatched. Any earlier tuple we skipped already had a matched robot or package, and matched robots/packages never become free again, so a skipped tuple can never win a later round either.Phase 3: Build `assign_robots`
We track
assigned_item[robot_idx](initialized to-1while free) anditem_taken[item_idx](initialized toFalse). Even though all packages are guaranteed reachable here, we skipsteps == -1defensively — otherwise-1would sort ahead of valid distances like0and1!def assign_robots(grid: list[list[int]], robots: list[list[int]], items: list[list[int]]) -> list[int]: num_robots = len(robots) # Phase 1: Run one BFS per robot to collect all (steps, robot_idx, item_idx) candidate pairs. candidate_pairs: list[tuple[int, int, int]] = [] for robot_idx in range(num_robots): dist_grid = _bfs_distances(grid, robots[robot_idx]) for item_idx in range(num_robots): item_row, item_col = items[item_idx] steps = dist_grid[item_row][item_col] # Skip unreachable items defensively so -1 never sorts ahead of real distances >= 0. if steps == -1: continue candidate_pairs.append((steps, robot_idx, item_idx)) # Phase 2: Sort tuples ascending so Python compares `steps`, then `robot_idx`, then `item_idx` — # matching the exact priority and tie-breaking order of the round-by-round rules. candidate_pairs.sort() # Phase 3: Greedily lock in each pair whose robot and item are both still unassigned. # assigned_item[i]: item index assigned to robot i, or -1 while robot i is still free. assigned_item = [-1] * num_robots item_taken = [False] * num_robots for steps, robot_idx, item_idx in candidate_pairs: if assigned_item[robot_idx] == -1 and not item_taken[item_idx]: assigned_item[robot_idx] = item_idx item_taken[item_idx] = True return assigned_itemTrace Example 2 step by step
Let's trace Example 2 (
robots = [[0, 0], [1, 3]],items = [[0, 2], [2, 0]]):1. BFS from Robot 0 at (0, 0): - distance to Item 0 at (0, 2) = 6 -> pair (6, 0, 0) - distance to Item 1 at (2, 0) = 2 -> pair (2, 0, 1) 2. BFS from Robot 1 at (1, 3): - distance to Item 0 at (0, 2) = 2 -> pair (2, 1, 0) - distance to Item 1 at (2, 0) = 4 -> pair (4, 1, 1) 3. Sort candidate_pairs: [(2, 0, 1), (2, 1, 0), (4, 1, 1), (6, 0, 0)] 4. Single greedy scan: - (2, 0, 1): Robot 0 free, Item 1 free -> MATCH! assigned_item = [1, -1], item_taken = [False, True] - (2, 1, 0): Robot 1 free, Item 0 free -> MATCH! assigned_item = [1, 0], item_taken = [True, True] - (4, 1, 1): Robot 1 already matched -> skip - (6, 0, 0): Robot 0 already matched -> skip Result: [1, 0]Complete solution
Putting both functions together gives the complete solution:
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def _bfs_distances(grid: list[list[int]], start: list[int]) -> list[list[int]]: """Return a grid of shortest 4-directional step counts from `start` (-1 if unreachable).""" num_rows = len(grid) num_cols = len(grid[0]) start_row, start_col = start # dist[r][c]: fewest steps from `start` to (r, c), or -1 if not yet reached / blocked. dist = [[-1] * num_cols for _ in range(num_rows)] dist[start_row][start_col] = 0 # queue: FIFO deque of (row, col) cells expanding outward wave by wave (0 steps, 1 step, ...). queue = deque([(start_row, start_col)]) directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] while queue: row, col = queue.popleft() for d_row, d_col in directions: next_row = row + d_row next_col = col + d_col # Because every move costs 1 step, the first time BFS reaches a free cell (`dist == -1`) # is guaranteed to be via a shortest path; setting `dist` immediately avoids re-queuing. if ( 0 <= next_row < num_rows and 0 <= next_col < num_cols and grid[next_row][next_col] == 0 and dist[next_row][next_col] == -1 ): dist[next_row][next_col] = dist[row][col] + 1 queue.append((next_row, next_col)) return dist def assign_robots(grid: list[list[int]], robots: list[list[int]], items: list[list[int]]) -> list[int]: num_robots = len(robots) # Phase 1: Run one BFS per robot to collect all (steps, robot_idx, item_idx) candidate pairs. candidate_pairs: list[tuple[int, int, int]] = [] for robot_idx in range(num_robots): dist_grid = _bfs_distances(grid, robots[robot_idx]) for item_idx in range(num_robots): item_row, item_col = items[item_idx] steps = dist_grid[item_row][item_col] # Skip unreachable items defensively so -1 never sorts ahead of real distances >= 0. if steps == -1: continue candidate_pairs.append((steps, robot_idx, item_idx)) # Phase 2: Sort tuples ascending so Python compares `steps`, then `robot_idx`, then `item_idx` — # matching the exact priority and tie-breaking order of the round-by-round rules. candidate_pairs.sort() # Phase 3: Greedily lock in each pair whose robot and item are both still unassigned. # assigned_item[i]: item index assigned to robot i, or -1 while robot i is still free. assigned_item = [-1] * num_robots item_taken = [False] * num_robots for steps, robot_idx, item_idx in candidate_pairs: if assigned_item[robot_idx] == -1 and not item_taken[item_idx]: assigned_item[robot_idx] = item_idx item_taken[item_idx] = True return assigned_item✅ Submit now — all tests should pass.
Intuition & how it works
Picture a warehouse floor with shelving walls (1s), k robots, and k packages waiting for collection. First, every robot needs to know its actual walking distance around walls to every package — we find that by expanding outward from each robot's cell using Breadth-First Search (BFS) (a graph search that explores cells wave by wave in order of 0 steps, 1 step, 2 steps, using a FIFO queue, a first-in, first-out line where the earliest cell added is explored next). Second, the dispatcher pairs up the single closest (robot, item) pair anywhere in the building first, removes both from consideration, and repeats — a greedy algorithm (making the best immediate local choice at each step without backtracking). By packing every pair into a 3-tuple (steps, robot_idx, item_idx) and sorting once, lexicographical tuple comparison (comparing the first element, then the second on ties, then the third) orders all k^2 pairs in exact round-by-round priority so one left-to-right scan completes all matches.
Why do simpler shortcuts fail? You cannot compute distances with Manhattan distance (abs(r1 - r2) + abs(c1 - c2), the grid distance when no walls exist) because a wall between a robot and a nearby cell can force a long detour around the room. And you cannot simply loop robot_idx = 0, 1, ... letting each robot claim its closest remaining package in index order: when Robot 1 stands 0 steps from a package while Robot 0 is farther away, Robot 1 must claim that package first.
Let's trace Example 3 (grid = [[0, 0, 0]], robots = [[0, 2], [0, 0]], items = [[0, 1], [0, 0]]):
Floor layout: col 0 col 1 col 2
R1 & I1 I0 R0
Step 1 (BFS distances from each robot):
From R0 at (0,2): to I0(0,1) = 1 step, to I1(0,0) = 2 steps
From R1 at (0,0): to I0(0,1) = 1 step, to I1(0,0) = 0 steps
Step 2 (Sort all (steps, robot_idx, item_idx) tuples):
[(0, 1, 1), (1, 0, 0), (1, 1, 0), (2, 0, 1)]
^ 0 steps wins Round 1 even though R1 > R0!
Step 3 (Greedy scan):
(0, 1, 1) -> R1 & I1 both free -> R1 gets I1
(1, 0, 0) -> R0 & I0 both free -> R0 gets I0
Remaining tuples skipped -> assigned_item = [0, 1]
Complexity
Let C = m * n be the total number of cells in the grid and k be the number of robots (and packages).
- Time:
O(k * C + k^2 log k). We run BFS once from each of thekrobots; each BFS visits each of theCgrid cells at most once and checks4neighbors inO(1)time (O(k * C)total). Building thek^2tuples takesO(k^2), sorting thosek^2tuples takesO(k^2 log(k^2)) = O(k^2 log k)comparisons, and the final greedy scan checks each tuple inO(1)time. At the maximum constraints (m = n = 50,k = 50), that is at most125,000cell visits plus sorting2,500tuples. - Space:
O(C + k^2). Each_bfs_distancescall allocates onem x ngrid (O(C)) that can be reclaimed before the next robot's BFS, whilecandidate_pairsstores up tok^2tuples (O(k^2)).
Edge cases
- Robot standing directly on a package (
steps == 0, Example 3): BFS setsdist[start_row][start_col] = 0, so(0, robot_idx, item_idx)sorts ahead of every positive-distance pair regardless of robot index. - Multiple pairs tied at the same distance (Example 1): Tuple comparison
(steps, robot_idx, item_idx)breaks ties by smallestrobot_idxfirst and smallestitem_idxsecond, matching the rules without custom comparator logic. - Walls forcing detours (Example 2): BFS explores only
grid[r][c] == 0cells in 4 cardinal directions, accurately measuring winding paths up tom * n - 1steps. - Greedy vs. minimum total travel: Dispatching strictly follows greedy closest-pair rounds even when that makes the fleet's combined travel larger (for example, on a
1 x 6aisle with robots at0, 3and packages at2, 5, greedy pairs(R1, I0)at1step and leaves(R0, I1)to walk5steps for6total, whereasR0 -> I0, R1 -> I1would total4). 1 x 1grid (m = n = k = 1): Robot0and package0share(0, 0)at0steps, returning[0].
Common mistakes
- Using Manhattan distance (
abs(dr) + abs(dc)) instead of BFS: Ignores walls (1s) and fails whenever an obstacle blocks the direct route (as in Example 2). - Allowing 8-directional (diagonal) movement: Robots may only step north, south, east, or west; adding diagonal offsets undercounts steps by half on diagonal routes.
- Matching robots one by one in index order (
for i in range(k): pick nearest item): Lets Robot0claim a package several steps away even when Robot1is much closer to that same package. - Marking BFS cells visited when popping instead of when pushing: If
dist[next_row][next_col]is not updated right beforequeue.append, multiple neighbors push the same cell ontoqueuerepeatedly, blowing up time and memory on open grids. - Forgetting
if steps == -1: continuewhen extending to unreachable grids: Because-1 < 0, an unreachable sentinel-1would sort first and falsely match an impossible pair ahead of valid ones!
Alternative approaches
- Per-package BFS: Running BFS from each of the
kpackages instead of thekrobots performs the exact sameO(k * C)work here; in a variant with10packages and500robots, running BFS from the smaller side (min(len(robots), len(items))searches) is dramatically faster. - Literal
krounds without sorting: Store thek x kdistance matrix and runkiterations scanning all remaining(i, j)pairs for the minimum(dist[i][j], i, j). That takesO(k * C + k^3)time, which still easily passes fork <= 50(50^3 = 125,000) and serves as a clean reference check in tests.
Follow-up questions
- How would the algorithm change if you needed to minimize the total distance traveled across the entire fleet? Greedy closest-pair matching can trap the final robot with a long cross-warehouse trek. Minimizing the sum of assigned distances between two equal-sized sets is minimum-weight bipartite matching (pairing each left node to one right node to minimize total cost), which can be solved optimally in
O(k^3)time after building the same BFS distance matrix using the Hungarian algorithm (orscipy.optimize.linear_sum_assignmentin Python scientific stacks). - How would you compute shortest distances if different floor cells had different positive movement costs? When step weights vary (such as
1second on smooth concrete vs.4seconds on a ramp), a plain FIFO queue no longer pops cells in ascending order of accumulated travel time. Replace_bfs_distanceswith Dijkstra's algorithm — a shortest-path search that pops the smallest accumulated cost first from a min-heap (heapq) — running inO(C log C)per robot while leaving tuple sorting and greedy matching unchanged. - How would you adapt the code when robot and item counts differ or when walls completely isolate certain items? Clarify that unmatched robots should output
-1. Because our code already initializesassigned_item = [-1] * num_robotsand skips unreachable pairs viaif steps == -1: continue, changing the inner loop tofor item_idx in range(len(items))(withitem_taken = [False] * len(items)) handles unequal fleet/package counts and walled-off rooms directly, leavingassigned_item[i] == -1whenever robotihas no reachable unclaimed package left.
Follow-up questions
- How would the algorithm change if you needed to minimize the total distance traveled across the entire fleet?
- How would you compute shortest distances if different floor cells had different positive movement costs?
- How would you adapt the code when robot and item counts differ or when walls completely isolate certain items?
Similar questions
- Vertical Axis Symmetry for Point Multisets
- Missing Integer Ranges Between Intervals
- Interval List Overlaps
- Largest Path Sum Across an N-ary Tree
- Dynamic Weighted Key Sampler
- Cluster Coordinates by Euclidean Distance Limit
More Nuro interview questions
- Concurrent 25 FPS Video Playback Engine Hard
- Object-Oriented K-Way Merger for Timestamped Streams Hard
- Vertical Axis Symmetry for Point Multisets Hard Pro
- Lock-Based Concurrency vs. MVCC for Versioned Key-Value Storage Hard Pro
- Deduplicated Run Duration Across Overlapping Intervals Easy Pro
- Buffered 25 FPS Video Playback Over Non-Thread-Safe Calls Hard Pro
- Multi-Tenant Webhook Delivery and Fleet Telemetry Pipeline Hard Pro
- DAG Workflow Scheduler for Weekly Autonomous Driving Simulations Medium Pro
- Multi-Tenant Distributed GPU Training Cluster Hard Pro
- End-to-End Project Deep Dive: Architecture, Ownership, and Debugging Hard Pro