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
dead ends, 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.
Example 1:
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" Output: 6 Explanation: A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, because the wheels of the lock become stuck after the display becomes the dead end "0102".
Example 2:
Input: deadends = ["8888"], target = "0009" Output: 1 Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".
Example 3:
Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" Output: -1 Explanation: We cannot reach the target without getting stuck.
Constraints:
1 <= deadends.length <= 500
deadends[i].length == 4
target.length == 4
deadends
.target
and deadends[i]
consist of digits only.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to opening the lock tries every single possible combination until we find the correct one. We will start with the initial state, then systematically try every single combination until we reach our target or have exhausted all possibilities.
Here's how the algorithm would work step-by-step:
def open_the_lock_brute_force(deadends, target):
initial_combination = '0000'
if initial_combination in deadends:
return -1
visited_combinations = {initial_combination}
queue = [initial_combination]
number_of_steps = 0
while queue:
queue_length = len(queue)
for _ in range(queue_length):
current_combination = queue.pop(0)
if current_combination == target:
return number_of_steps
# Explore all possible next combinations
for index in range(4):
digit = int(current_combination[index])
# Try incrementing the digit
incremented_combination = current_combination[:index] + str((digit + 1) % 10) + current_combination[index+1:]
if incremented_combination not in deadends and incremented_combination not in visited_combinations:
queue.append(incremented_combination)
visited_combinations.add(incremented_combination)
# Try decrementing the digit
decremented_combination = current_combination[:index] + str((digit - 1 + 10) % 10) + current_combination[index+1:]
if decremented_combination not in deadends and decremented_combination not in visited_combinations:
# Ensure that the next combination is valid
queue.append(decremented_combination)
visited_combinations.add(decremented_combination)
number_of_steps += 1
return -1
The challenge is to find the shortest path to open a lock, given some forbidden combinations. We use a method that explores possible combinations systematically, like ripples spreading outwards from the starting point, until we reach the target.
Here's how the algorithm would work step-by-step:
def open_the_lock(dead_ends, target):
start_combination = "0000"
if start_combination in dead_ends:
return -1
queue = [(start_combination, 0)]
visited = {start_combination}
while queue:
current_combination, moves = queue.pop(0)
if current_combination == target:
return moves
# Iterate through each digit in the combination.
for index in range(4):
digit = int(current_combination[index])
# Generate the next possible combination by incrementing
incremented_digit = (digit + 1) % 10
incremented_combination = current_combination[:index] + str(incremented_digit) + current_combination[index + 1:]
if incremented_combination not in visited and incremented_combination not in dead_ends:
# Avoid revisiting combinations.
visited.add(incremented_combination)
queue.append((incremented_combination, moves + 1))
# Generate the next possible combination by decrementing
decremented_digit = (digit - 1 + 10) % 10
decremented_combination = current_combination[:index] + str(decremented_digit) + current_combination[index + 1:]
if decremented_combination not in visited and decremented_combination not in dead_ends:
# Avoid revisiting combinations.
visited.add(decremented_combination)
queue.append((decremented_combination, moves + 1))
# If target not reachable
return -1
Case | How to Handle |
---|---|
deadends is null or empty | Treat an empty deadends array as no restrictions, allowing the search to proceed normally from '0000'. |
target is null or empty | Return -1 if target is null or empty since a target is needed to unlock. |
target is equal to '0000' and '0000' is not in deadends | Return 0 immediately because the lock is already open and no moves are needed. |
target is in deadends | Return -1 immediately as the target state is unreachable. |
'0000' is in deadends | Return -1 immediately because the lock cannot be opened if the starting position is blocked. |
All possible combinations are deadends | The BFS should terminate and return -1, since no path to the target exists. |
deadends contains duplicate entries | The Set used to store deadends will handle duplicates automatically without affecting the algorithm's correctness. |
Very large number of deadends | The BFS approach ensures that we don't revisit previously visited states, preventing cycles and still finding the optimal solution, but might have memory limitations. |