Compute shortest path to collect all keys
Company: Airbnb
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in state-space representation, graph search and shortest-path techniques, compact state encoding (such as bitmasking), and algorithmic time/space complexity analysis within the Coding & Algorithms domain.
Constraints
- 1 <= m, n <= 30
- grid[i][j] is one of '#', '.', '@', 'a' - 'f', or 'A' - 'F'
- There is exactly one starting cell '@'
- There are at most 6 keys, and each door matches a key with the same letter ignoring case
Examples
Input: (["@.a..","###.#","b.A.B"],)
Expected Output: 8
Explanation: You must collect 'a' first, then pass through door 'A' to eventually reach 'b'. The shortest valid route takes 8 steps.
Input: (["@..aA","..B#.","....b"],)
Expected Output: 6
Explanation: Collect 'a' in 3 steps, then move through door 'A' and continue to 'b'. The minimum is 6.
Input: (["@Aa"],)
Expected Output: -1
Explanation: Door 'A' blocks the only path to key 'a', so the key can never be collected.
Input: (["@"],)
Expected Output: 0
Explanation: There are no keys in the grid, so zero steps are needed.
Input: (["@...a","###A#","b...."],)
Expected Output: 10
Explanation: The lower row is only reachable through door 'A', so you must collect 'a' first and then go back to unlock the route to 'b'.
Hints
- A normal BFS over just (row, col) is not enough, because arriving at the same cell with different keys collected can lead to different future moves.
- Since there are at most 6 keys, encode the collected keys as a bitmask and use (row, col, key_mask) as your BFS state and visited marker.