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:

  1. Out of every pair (i, j) where robot i and package j are both still unmatched, select the pair with the minimum travel distance.
  2. Break distance ties by choosing the smallest robot index i, and break any remaining tie by choosing the smallest package index j.
  3. Permanently match robot i with package j so 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 <= 50 where m = len(grid) and n = len(grid[0]) (all rows have length n).
  • Every grid[r][c] is either 0 (passable) or 1 (wall).
  • 1 <= k <= 50 with len(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 (0 steps).
  • Every package is reachable from every robot along passable cells.

Step-by-step walkthrough

  1. Understand the two subproblems: obstacle distances and greedy rounds

    We have an m x n warehouse of passable cells (0) and walls (1), k robots, and k packages. We need to return assigned_item of length k where assigned_item[i] records the package index matched to robot i.

    Solving this cleanly means separating two distinct tasks:

    1. 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 distance abs(r1 - r2) + abs(c1 - c2).
    2. 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 index i when distances tie),
      • then item_idx (smallest package index j if 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)!
    
  2. 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 * k searches over up to m * n cells), and - run k separate rounds, rescanning all k * k pairs every round (k^3 comparisons).

    Notice the wasted work in step 1: all k searches starting from robot_0 explore the exact same grid from the exact same cell! Running one search per robot computes the shortest distance to every cell — and therefore to all k packages — in a single pass.

  3. Phase 1: Find shortest paths around walls with one BFS per robot

    Because every move costs 1 step, Breadth-First Search (BFS) — expanding cells wave by wave using a first-in, first-out queue (collections.deque) — visits cells at 0 steps, then 1 step, then 2 steps, and so on. The first time BFS reaches any passable cell is guaranteed to be along a shortest path.

    We allocate a 2D table dist filled with -1. That -1 acts 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 dist
    
  4. Phase 2: Turn `k` greedy rounds into one sorted pass

    After calling _bfs_distances once per robot, we pack every reachable pair into a 3-tuple:

    (steps, robot_idx, item_idx)
    

    When Python sorts tuples, it compares element 0 first (steps), breaks ties with element 1 (robot_idx), and breaks remaining ties with element 2 (item_idx). That matches the dispatch tie-breakers automatically!

    Why does scanning the sorted list once produce the exact same matches as k separate rounds? - Round 1 chooses the smallest tuple overall — index 0 of 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.

  5. Phase 3: Build `assign_robots`

    We track assigned_item[robot_idx] (initialized to -1 while free) and item_taken[item_idx] (initialized to False). Even though all packages are guaranteed reachable here, we skip steps == -1 defensively — otherwise -1 would sort ahead of valid distances like 0 and 1!

    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
    
  6. Trace 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]
    
  7. 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 the k robots; each BFS visits each of the C grid cells at most once and checks 4 neighbors in O(1) time (O(k * C) total). Building the k^2 tuples takes O(k^2), sorting those k^2 tuples takes O(k^2 log(k^2)) = O(k^2 log k) comparisons, and the final greedy scan checks each tuple in O(1) time. At the maximum constraints (m = n = 50, k = 50), that is at most 125,000 cell visits plus sorting 2,500 tuples.
  • Space: O(C + k^2). Each _bfs_distances call allocates one m x n grid (O(C)) that can be reclaimed before the next robot's BFS, while candidate_pairs stores up to k^2 tuples (O(k^2)).

Edge cases

  • Robot standing directly on a package (steps == 0, Example 3): BFS sets dist[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 smallest robot_idx first and smallest item_idx second, matching the rules without custom comparator logic.
  • Walls forcing detours (Example 2): BFS explores only grid[r][c] == 0 cells in 4 cardinal directions, accurately measuring winding paths up to m * n - 1 steps.
  • 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 6 aisle with robots at 0, 3 and packages at 2, 5, greedy pairs (R1, I0) at 1 step and leaves (R0, I1) to walk 5 steps for 6 total, whereas R0 -> I0, R1 -> I1 would total 4).
  • 1 x 1 grid (m = n = k = 1): Robot 0 and package 0 share (0, 0) at 0 steps, 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 Robot 0 claim a package several steps away even when Robot 1 is 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 before queue.append, multiple neighbors push the same cell onto queue repeatedly, blowing up time and memory on open grids.
  • Forgetting if steps == -1: continue when extending to unreachable grids: Because -1 < 0, an unreachable sentinel -1 would sort first and falsely match an impossible pair ahead of valid ones!

Alternative approaches

  • Per-package BFS: Running BFS from each of the k packages instead of the k robots performs the exact same O(k * C) work here; in a variant with 10 packages and 500 robots, running BFS from the smaller side (min(len(robots), len(items)) searches) is dramatically faster.
  • Literal k rounds without sorting: Store the k x k distance matrix and run k iterations scanning all remaining (i, j) pairs for the minimum (dist[i][j], i, j). That takes O(k * C + k^3) time, which still easily passes for k <= 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 (or scipy.optimize.linear_sum_assignment in Python scientific stacks).
  • How would you compute shortest distances if different floor cells had different positive movement costs? When step weights vary (such as 1 second on smooth concrete vs. 4 seconds on a ramp), a plain FIFO queue no longer pops cells in ascending order of accumulated travel time. Replace _bfs_distances with Dijkstra's algorithm — a shortest-path search that pops the smallest accumulated cost first from a min-heap (heapq) — running in O(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 initializes assigned_item = [-1] * num_robots and skips unreachable pairs via if steps == -1: continue, changing the inner loop to for item_idx in range(len(items)) (with item_taken = [False] * len(items)) handles unequal fleet/package counts and walled-off rooms directly, leaving assigned_item[i] == -1 whenever robot i has no reachable unclaimed package left.

Follow-up questions

Similar questions

More Nuro interview questions

All 29 Nuro questions →