Shortest Path to Collect Every Key in a Warehouse Grid
Last updated: November 29, 2026
Quick Overview
A warehouse grid has walls '#', open floor '.', a start '@', lowercase keys 'a' to 'f', and uppercase locked doors that need the matching key. Return the fewest steps to collect every key, or -1.
Meta
November 29, 20260
0
0 solved
A warehouse grid has walls '#', open floor '.', a start '@', lowercase keys 'a' to 'f', and uppercase locked doors that need the matching key. Return the fewest steps to collect every key, or -1.
BFS over an expanded state space in the style of Meta's hardest onsite coding questions, loosely framed as planning a robot route in a fulfillment warehouse. The interviewer is checking that you realize position alone is not enough state and that you encode the keys held as a bitmask.
What the Interviewer Expects
- Identifies the state as (row, col, keys held)
- Encodes keys as a bitmask
- Runs BFS over states with a visited set on full states
- Blocks moves into doors unless the bit for that key is set
- Bounds the state space at R * C * 2^K
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would A* with a good heuristic help here?
- What if picking up a key costs extra time?
- How would you handle up to 26 keys?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: list of strings. Output: minimum number of 4-directional moves to hold every key, or -1. Up to 6 keys, grid up to 30 x 30. Stepping on a key picks it up for free....
High-Level Design
Plain BFS on cells fails because returning to a cell with more keys is a genuinely different situation. Make the state (r, c, mask), where bit i of mask means key i is held. From each state, try fou...