15% off all plans & roadmaps Use code
See plansLeetCode 752 · Solution & editorial
A lock state is a four-character string whose characters are digits from 0 through 9. The lock begins in state "0000". Turning one wheel by one step changes exactly one character: a digit can increase or decrease by 1, and the ends wrap around, so 9 can become 0 and 0 can become 9.
Open the Lock is a Graph Traversal Patterns (DFS & BFS) problem, in the Bidirectional BFS (BFS optimization for known source & target) subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Optimize BFS by searching from both source and target simultaneously. Reduce time complexity significantly.
The reference solution runs in O(deadends.length + 10^4) time and O(deadends.length + 10^4) space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Open the Lock is a Graph Traversal Patterns (DFS & BFS) problem, in the Bidirectional BFS (BFS optimization for known source & target) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.