← Questions

Shortest path to collect all keys

0
AirbnbCodingLast asked Aug 2025

A coding interview question asked in Airbnb's coding round, last asked Aug 2025. It tests bfs, bitmask and grids.

A grid holds walls, empty cells, one start cell, keys (lowercase letters) and locks (the matching uppercase letters). You move one cell up, down, left or right per step. You can pass a lock only once you have picked up its key; keys stay with you once collected. Return the fewest steps to collect every key in the grid, or -1 if that is impossible.

Interface

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

  • shortest_path_all_keys(grid: list[str]) -> int — characters are '@' (start), '#' (wall), '.' (empty), 'a'–'f' (keys) and 'A'–'F' (locks).

Example

shortest_path_all_keys(["@aA.b"])   ->  4     # pick up a, pass A, reach b
shortest_path_all_keys(["a.@A.b"])  ->  7     # 2 steps left for a, then 5 steps right to b
shortest_path_all_keys(["@Aa"])     ->  -1    # the only key is behind its own lock
shortest_path_all_keys(["@.#", "..."])  ->  0 # no keys at all

Constraints

  • The grid is at most 30 × 30.
  • At most 6 keys, each with at most one lock; exactly one start.

Clarifying questions

  • Can a lock exist without its key, or a key without a lock?
  • What is the answer when there are no keys?
  • Can I walk over the start cell and keys again after collecting them?
  • How many distinct keys at most?

What a strong answer covers

  • Breadth-first search over states (row, column, keys held), with the keys as a bitmask; the answer is the first time the mask is complete.
  • A visited set over all three parts: the same cell is worth revisiting with more keys.
  • O(rows · cols · 2^K) time and space, which is small for K <= 6.
  • Edge cases: no keys, unreachable keys, a key behind its own lock.
  • As an alternative, shortest distances between keys first, then a search over the order of collection.

Follow-ups

  • Return the path, not just its length.
  • Some cells cost more to cross. What replaces BFS?
  • Keys are used up when they open a lock. What changes in the state?

Where it's asked

  • Airbnb · Coding · Last asked Aug 202545 min · Live coding, one or two rounds, from the same pool as the screen

What it tests

bfs · bitmask · grids

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