DIY: Open Lock
Solve the interview question "Open Lock" in this lesson.
We'll cover the following
Problem statement
You have an old lock in front of you with four circular wheels. Each wheel has ten 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.
Initially, the lock starts at '0000'
, a string representing the state of the four wheels.
You are given a list of dead ends named deadends
. If the lock displays any of these codes, the lock’s wheels 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 not possible.
Input
The input will be a list of strings, deadends
, and a string, target
. The following is an example input:
deadends = ["2110","0202","1222","2221","1010"]
target = "2010"
Output
The output will be an integer value representing the minimum total number of turns required to open the lock. The following is an example output for the above input:
3
The valid moves to open the lock in minimum moves would be "0000" -> "1000" -> "2000" -> "2010"
Coding exercise
Implement the openLock(deadends, target)
function, where deadends
is the list of strings and target
is the string. The function will return a single integer value representing the minimum total number of turns required to open the lock.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.