Collect Every Key in a Locked Maze With the Fewest Steps

Last updated: November 29, 2026

Quick Overview

A grid maze contains walls '#', open cells '.', a start '@', lowercase keys a to f, and matching uppercase locks. You can pass a lock only if you hold its key. Return the fewest steps to collect all keys, or -1.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


A grid maze contains walls '#', open cells '.', a start '@', lowercase keys a to f, and matching uppercase locks. You can pass a lock only if you hold its key. Return the fewest steps to collect all keys, or -1.

A demanding Google onsite BFS where the right state is (position, keys held) encoded as a bitmask. The interviewer is checking whether you see that revisiting a cell is useful once you hold more keys, and that the state space is still small enough.

What the Interviewer Expects
  • Define state as (row, col, key bitmask)
  • Use BFS since every step costs 1
  • Allow revisiting cells with a different key set
  • Block movement into locks whose key bit is missing
  • Return when the mask has all key bits set
Key Topics to Cover
BFS with state
bitmask
grid
shortest path
state explosion
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
  • What if there are up to 26 keys?
  • Precompute distances between key positions and run Dijkstra over (key, mask).
  • What if keys are consumed when used on a lock?
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, at most 6 keys.
  • Moves: 4 directions, not into walls, not into a lock without its key.
  • Output: minimum steps to hold all keys, or -1....
High-Level Design

Picking up a key changes what is reachable, so position alone is not a valid BFS state. I use (r, c, mask) where bit ii of mask means key ii is held. The visited set is over these triples. From ...


Submit Your Answer
Markdown supported