Open the Lock
MediumThis is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.
Question
You have a combination lock with 4 wheels. Each wheel shows a digit from 0 to 9. A turn moves one wheel one step forward or one step back. The wheels wrap around between 9 and 0.
The lock always starts at "0000". Some combinations are jammed. You can never land on one of those. Return the fewest turns it takes to reach the target combination. If you can't reach it, return -1.
Input: jammed = [], target = "0003"
Output: 3
Turn the last wheel forward three times: "0000" => "0001" => "0002" => "0003".
Input: jammed = ["0001", "0010", "0100", "1000"], target = "0002"
Output: 4
Turning any wheel forward from "0000" lands on a jammed combination. So you have to take a detour. One way is "0000" => "0090" => "0091" => "0092" => "0002".
Input: jammed = ["4321"], target = "4321"
Output: -1
The target itself is jammed. So you can never reach it.
Clarify the problem
What are some questions you'd ask an interviewer?
Understand the problem
Remember to understand the problem and plan your approach before you start coding.