Imagine you're a master thief standing before a sophisticated 4-digit combination lock. Each digit can be rotated from 0 to 9, and the wheels wrap around (so 9 becomes 0 and vice versa).

The lock starts at "0000" and you need to reach a specific target combination to unlock it. However, there's a catch - certain combinations are deadends that will trigger an alarm and lock you out forever!

Your mission: Find the minimum number of wheel turns needed to reach the target, or return -1 if it's impossible.

Rules:

  • Each move rotates exactly one wheel by one position
  • Wheels wrap around: 0 โ†’ 9 and 9 โ†’ 0
  • Avoid all deadend combinations
  • Find the shortest path from "0000" to target

Input & Output

example_1.py โ€” Basic Case
$ Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
โ€บ Output: 6
๐Ÿ’ก Note: The shortest path is: 0000 โ†’ 1000 โ†’ 1100 โ†’ 1200 โ†’ 1201 โ†’ 1202 โ†’ 0202. We avoid deadends and find the minimum 6 moves.
example_2.py โ€” Impossible Case
$ Input: deadends = ["8888"], target = "0009"
โ€บ Output: 1
๐Ÿ’ก Note: We can turn the last wheel from 0000 to 0009 in just 1 move. The deadend 8888 doesn't block our path.
example_3.py โ€” Blocked Start
$ Input: deadends = ["0000"], target = "8888"
โ€บ Output: -1
๐Ÿ’ก Note: The starting position 0000 is a deadend, so we cannot make any moves. Return -1 as it's impossible.

Constraints

  • 1 โ‰ค deadends.length โ‰ค 500
  • deadends[i].length == 4
  • target.length == 4
  • target will not be in the list deadends
  • target and deadends[i] consist of digits only

Visualization

Tap to expand
Floor 0: Start (0000)Floor 1: Distance 1Floor 2: Distance 2TARGET!
Understanding the Visualization
1
Start at Ground Floor
Begin at room 0000 on floor 0
2
Explore Floor 1
Visit all rooms reachable in 1 move
3
Explore Floor 2
Visit all rooms reachable in 2 moves
4
Continue Until Target
The floor number when we find the target is our answer
Key Takeaway
๐ŸŽฏ Key Insight: BFS explores by distance levels, guaranteeing the shortest path to any reachable combination!
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
95.4K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen