Open the Lock
MediumExtra practice. This problem has no walkthrough slides. Try solving it with the pattern template on your own, and lean on the hints if you get stuck.
Question
You have a 4-wheel combination lock. Every wheel holds a digit from 0 to 9, and turning a wheel moves it one step forward or one step back, wrapping around between 9 and 0.
The lock always starts at "0000". Some combinations are jammed and can't be turned into at all. Return the minimum number of turns needed to reach a target combination without ever landing on a jammed one, or -1 if it can't be done.
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 single wheel forward one step from "0000" lands on a jammed combination, so reaching "0002" takes a longer detour through combinations that aren't jammed.
Input: jammed = ["4321"], target = "4321"
Output: -1
The target combination itself is jammed, so it can never be reached.
Clarify the problem
What are some questions you'd ask an interviewer?
Understand the problem
Take a moment to understand the problem and think of your approach before you start coding.