669. Combination Lock

A vault door has four rotating dials, each showing a digit from 0 to 9, and the dials are read as a four-character string such as "0370". One turn rotates exactly one dial by one position, forwards or backwards, and the dials wrap around: after 9 comes 0, and before 0 comes 9. The dials start at "0000".

The security log deadends lists dial readings that jam the mechanism: if the dials ever show one of those readings, no further turns are possible from it, so such a reading may never be used, not even as the first or last one. The log may repeat entries. Return the minimum number of turns that makes the dials show target, or -1 if it cannot be done (this includes the case where the starting reading or the target is itself jammed). The log can be long, so checking membership must be fast.

Example 1

Input:
deadends = ["1000","0100","0010"], target = "0110"
Output:
4
Explanation:

The two direct routes to the target pass through the jammed readings 0100 and 0010, and the number of turns must be even, so the shortest legal route takes 4 turns, for example 0000, 0001, 0101, 0111, 0110.

Example 2

Input:
deadends = ["0001","0009","0010","0090","0100","0900","1000","9000"]target = "5555"
Output:
-1
Explanation:

All eight readings one turn away from 0000 are jammed, so the dials can never leave the start and the answer is -1.

Example 3

Input:
deadends = [], target = "0000"
Output:
0
Explanation:

The dials already show the target, so zero turns are needed.

Constraints

0 ≤ deadends.length ≤ 20000

every string in deadends and target has exactly 4 characters, each a digit

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O(D + 10^4)
Space
O(10^4)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…