Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Open the Lock

XPChallenge Points: 20
levelLevel: Medium

You are standing in front of a lock with 4 rotating wheels, each numbered from '0' to '9'.
Each wheel can rotate forward or backward by one step, and it wraps around (e.g., '9' → '0' or '0' → '9').

Your lock starts at "0000".
You are given a list of deadends — if the lock shows any of these combinations, it becomes stuck and can’t move further.

Your task is to find the minimum number of wheel turns required to reach the target combination.
If the target cannot be reached, return -1.

Example 1:

Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"

Output: 6

Explanation:

One valid path is: "0000" → "1000" → "1100" → "1200" → "1201" → "1202" → "0202".

Example 2:

Input: deadends = ["8888"], target = "0009"

Output: 1

Explanation:

Rotate the last wheel once: "0000" → "0009".

Example 3:

Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"

Output: -1

Explanation:

All possible paths lead to deadends, so it’s impossible to unlock.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result