Trains the technique from
LeetCode 1345Jump Game IVThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A row of lockers is numbered from 0 to label.length - 1, and label[i] is the code stencilled on locker i. Two lockers may carry the same code.
A porter starts at locker 0 and wants to reach the last locker. Standing at locker i, one move takes the porter to any single one of these:
i + 1, if that locker exists;i - 1, if that locker exists;j with j != i and label[j] == label[i], however far away it is.Return the fewest moves needed to reach the last locker. If the porter already starts there, the answer is 0.
Example 1
One route is locker 0 to locker 4, allowed because both are stencilled 4, and then locker 4 to locker 5. That is two moves.
Example 2
No two lockers share a code, so the porter walks 0 to 1 to 2 to 3 to 4, which is four moves.
Example 3
Locker 0 is already the last locker, so no move is needed.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def fewest_hops(label: list[int]) -> int:public int fewestHops(int[] label)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.