A technician is retuning a broadcast dial that currently reads the integer start and must be brought to read exactly goal. The technician's toolbox holds n calibration values, each of which may be applied any number of times, in any order. Applying calibration value v to the current reading x changes it to exactly one of x + v, x - v, or x XOR v (bitwise XOR); this counts as one adjustment. While retuning, the dial's display can only show a safe reading between 0 and 1000 inclusive after any adjustment -- the sole exception is that an adjustment which lands the reading exactly on goal is always permitted and immediately finishes the job, even if goal itself lies outside 0 to 1000. Any adjustment that would produce a reading outside [0, 1000] and is not exactly goal is illegal and may not be performed. Determine the minimum number of adjustments needed to retune the dial from start to goal, or report that it cannot be done.
start and goal.Print a single integer: the minimum number of adjustments required, or -1 if reaching goal from start is impossible.
Example 1
Input
3 3 5 7 4 6
Expected
2
Explanation
From start=4, one adjustment with each value reaches {7,1,9,11,3} -- none is 6 yet. From reading 1 (reached using value 3 as 4 XOR 3), a second adjustment using value 5 gives 1 + 5 = 6, which equals goal. So goal is reached in 2 adjustments, and no single adjustment from 4 reaches 6 directly, so 2 is minimal.
Example 2
Input
3 2 4 6 1 8
Expected
-1
Explanation
Every calibration value (2, 4, 6) is even. Adding or subtracting an even value never changes the parity (odd/even-ness) of the reading, and XORing with an even value never flips the reading's lowest bit either, so the parity of the reading is invariant under every legal adjustment. start=1 is odd and goal=8 is even, so goal can never be reached: the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →