Open the Lock - Breadth-First Search Pattern
Open the Lock in Java using the Breadth-First Search pattern: problem statement, approach, template, complexity, and interview tips.
Open the Lock
Problem Statement
Find the minimum number of turns to open a four-wheel combination lock while avoiding deadend states.
Pattern: Breadth-First Search
Explore nodes level by level using a queue, which finds the shortest path in unweighted graphs.
Use this pattern when you need level order, the minimum number of steps, or the shortest transformation in an unweighted structure.
Approach
- Enqueue the start node(s) and mark them visited.
- Process one full level at a time using the queue size.
- Enqueue unvisited neighbours and count levels as steps.
Pattern Template (Java)
Queue<Node> queue = new ArrayDeque<>();
queue.offer(start);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Node cur = queue.poll();
// process cur and enqueue its unvisited neighbours
}
// one level finished
}
Adapt this template to the exact rules of Open the Lock: decide what state you track, what condition moves the loop forward, and what the final answer is.
Complexity
O(V + E) time and O(V) space.
Interview Tips
- Mark nodes visited when enqueuing, not when dequeuing.
- Start from all sources at once for multi-source problems such as rotting oranges.
- Start with a brute-force idea, state its complexity, then explain how the Breadth-First Search pattern improves it.
- Walk through a small example and at least one edge case (empty input, a single element, duplicates).
Related Problems
Continue Learning
Parent: DSA Interview Learning Path | Previous: Word Ladder | Next: Minimum Depth of Binary Tree
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.