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
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

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
BFS
Bitmask
State space search
Grids
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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...


Submit Your Answer
Markdown supported