You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'.
Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
The key insight is to treat this as a shortest path problem in an unweighted graph. Each lock state is a node, and turning any wheel creates an edge to a neighboring state. BFS guarantees the minimum number of turns since all edges have equal weight (1 turn). Time: O(10⁴), Space: O(10⁴)
Common Approaches
Approach
Time
Space
Notes
✓
Breadth-First Search (Optimal)
O(10⁴)
O(10⁴)
Use BFS to find shortest path by exploring all states level by level
Brute Force DFS
O(10⁴)
O(10⁴)
Try all possible combinations using depth-first search
Breadth-First Search (Optimal) — Algorithm Steps
Start with '0000' in queue at distance 0
For each state, generate all 8 neighbors (4 wheels × 2 directions)
Add unvisited, non-deadend neighbors to queue
Return distance when target is found
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Level 0
Start with '0000' at distance 0
2
Level 1
Explore all states reachable in 1 move
3
Level 2
Find target at minimum distance
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_QUEUE 20000
#define MAX_STATES 10000
typedef struct {
char state[5];
int steps;
} QueueItem;
typedef struct {
char states[MAX_STATES][5];
int count;
} StateSet;
bool contains(StateSet* set, char* state) {
for (int i = 0; i < set->count; i++) {
if (strcmp(set->states[i], state) == 0) {
return true;
}
}
return false;
}
void addState(StateSet* set, char* state) {
if (!contains(set, state) && set->count < MAX_STATES) {
strcpy(set->states[set->count], state);
set->count++;
}
}
void getNeighbors(char* state, char neighbors[][5], int* count) {
*count = 0;
for (int i = 0; i < 4; i++) {
int digit = state[i] - '0';
// Rotate up
strcpy(neighbors[*count], state);
neighbors[*count][i] = '0' + (digit + 1) % 10;
(*count)++;
// Rotate down
strcpy(neighbors[*count], state);
neighbors[*count][i] = '0' + (digit + 9) % 10;
(*count)++;
}
}
int solution(char deadends[][5], int deadendCount, char* target) {
StateSet dead = {0};
for (int i = 0; i < deadendCount; i++) {
addState(&dead, deadends[i]);
}
if (contains(&dead, "0000")) {
return -1;
}
if (strcmp(target, "0000") == 0) {
return 0;
}
StateSet visited = {0};
addState(&visited, "0000");
QueueItem queue[MAX_QUEUE];
int front = 0, rear = 0;
strcpy(queue[rear].state, "0000");
queue[rear].steps = 0;
rear++;
while (front < rear) {
QueueItem current = queue[front++];
char neighbors[8][5];
int neighborCount;
getNeighbors(current.state, neighbors, &neighborCount);
for (int i = 0; i < neighborCount; i++) {
if (strcmp(neighbors[i], target) == 0) {
return current.steps + 1;
}
if (!contains(&dead, neighbors[i]) && !contains(&visited, neighbors[i])) {
addState(&visited, neighbors[i]);
strcpy(queue[rear].state, neighbors[i]);
queue[rear].steps = current.steps + 1;
rear++;
}
}
}
return -1;
}
int main() {
char line[1000];
fgets(line, sizeof(line), stdin);
// Parse deadends array
char deadends[1000][5];
int deadendCount = 0;
char* token = strtok(line, "[],\"\n ");
while (token != NULL && deadendCount < 1000) {
if (strlen(token) == 4) {
strcpy(deadends[deadendCount], token);
deadendCount++;
}
token = strtok(NULL, "[],\"\n ");
}
char target[5];
fgets(target, sizeof(target), stdin);
target[strcspn(target, "\n")] = 0;
int result = solution(deadends, deadendCount, target);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(10⁴)
Each of 10,000 possible states is visited at most once
n
2n
✓ Linear Growth
Space Complexity
O(10⁴)
Queue and visited set can contain all possible lock states
n
2n
✓ Linear Space
48.0K Views
MediumFrequency
~25 minAvg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.