Taro Logo

Open the Lock

Medium
eBay logo
eBay
0 views
Topics:
Graphs

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
  • target will not be in the list deadends.
  • target and deadends[i] consist of digits only.

Solution


Clarifying Questions

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:

  1. What is the maximum possible length of the `deadends` array?
  2. Can the `target` string ever be equal to one of the strings in the `deadends` array?
  3. Is it possible for the `deadends` array to be empty?
  4. If it is impossible to reach the target, what should the function return?
  5. Are the strings in `deadends` and `target` guaranteed to be valid 4-digit strings with digits between '0' and '9'?

Brute Force Solution

Approach

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:

  1. Start with the lock at '0000'.
  2. Try every possible next combination by changing one digit at a time. For instance, '0001', '0010', '0100', '1000', and so on.
  3. Keep track of all the combinations you've tried so you don't repeat them.
  4. If any of the combinations are not allowed (deadends), skip them.
  5. Continue generating new combinations by changing one digit of the previous combinations, one at a time.
  6. Repeat this process, checking each new combination to see if it's the target combination or if it's a deadend.
  7. Stop when you find the target combination, or when you have tried every possible combination without finding the target.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(1)The state space of the lock is constant; there are 10,000 possible combinations (0000 to 9999), regardless of the specific input (deadends or target). The algorithm explores this space systematically using a breadth-first search, potentially visiting each combination once. Therefore, the time complexity is bound by the size of the constant state space which is O(1). Even with many deadends, it won't exceed this limit.
Space Complexity
O(1)The plain English explanation focuses on generating and checking combinations. To keep track of tried combinations, a set (or similar data structure) is needed to avoid repetition. The maximum number of possible combinations for a 4-digit lock is 10^4 (10000). In the worst-case scenario, we might need to store almost all of these combinations in our visited set. This leads to a space complexity proportional to the number of possible combinations which is a constant. Therefore, the space complexity is O(1).

Optimal Solution

Approach

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:

  1. Start with the lock at its initial state (usually four zeros).
  2. Imagine exploring all possible combinations one turn at a time: turn any one of the four digits up or down.
  3. Keep track of the combinations you've already tried to avoid going in circles.
  4. As you explore, check if any combination is forbidden; if it is, skip it.
  5. Continue exploring layer by layer until you find the target combination. The number of layers you expanded represents the fewest number of turns needed.
  6. If you've explored all possible combinations and haven't found the target, it means it's impossible to reach from the starting state.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(1)The time complexity is O(1) because the problem space is fixed. Each digit in the combination lock can only be one of 10 digits (0-9). Since there are four digits, the maximum number of possible combinations is 10^4 = 10,000. The algorithm explores these combinations in a breadth-first search manner, potentially visiting each combination at most once. While the number of deadends provided can affect the run time, the total possible states is still capped at 10,000, making the time complexity constant.
Space Complexity
O(10000)The algorithm uses a queue to store combinations to explore and a set to track visited combinations. In the worst case, we might explore all possible combinations of the lock, which ranges from '0000' to '9999', resulting in 10000 unique combinations. The visited set will, in the worst-case scenario, store all 10000 combinations, each combination consisting of four characters. Thus, the space complexity is O(10000), which simplifies to O(1), because it represents a constant amount of memory no matter how large the input 'deadends' list may be. Because the amount of total combinations is fixed, this value represents a fixed upper bound for the auxiliary memory used by the algorithm.

Edge Cases

CaseHow to Handle
deadends is null or emptyTreat an empty deadends array as no restrictions, allowing the search to proceed normally from '0000'.
target is null or emptyReturn -1 if target is null or empty since a target is needed to unlock.
target is equal to '0000' and '0000' is not in deadendsReturn 0 immediately because the lock is already open and no moves are needed.
target is in deadendsReturn -1 immediately as the target state is unreachable.
'0000' is in deadendsReturn -1 immediately because the lock cannot be opened if the starting position is blocked.
All possible combinations are deadendsThe BFS should terminate and return -1, since no path to the target exists.
deadends contains duplicate entriesThe Set used to store deadends will handle duplicates automatically without affecting the algorithm's correctness.
Very large number of deadendsThe BFS approach ensures that we don't revisit previously visited states, preventing cycles and still finding the optimal solution, but might have memory limitations.