A night-shift sentry walks a fixed patrol loop and, at every step, radios back the label of whichever checkpoint they are currently standing at, building up a log of n checkpoint labels in visiting order (the sentry revisits many checkpoints many times over the course of the patrol). Security wants to know how tightly two particular checkpoints are interleaved in that log: given two distinct checkpoint labels that are each guaranteed to appear somewhere in the log, find the fewest number of steps between some visit to the first checkpoint and some visit to the second checkpoint — that is, the minimum value of |i − j| over every step index i at which the first label was radioed and every step index j at which the second label was radioed.
Line 1: a single integer n, the number of logged steps. Line 2: n space-separated lowercase strings, the checkpoint label radioed at each step, in order. Line 3: two space-separated lowercase strings w1 and w2, the two checkpoint labels to compare (w1 ≠ w2).
A single integer: the minimum step distance between any occurrence of w1 and any occurrence of w2 in the log.
Example 1
Input
5 alpha bravo charlie delta bravo delta alpha
Expected
3
Explanation
delta appears only at index 3 and alpha appears only at index 0, so the only possible distance between an occurrence of delta and an occurrence of alpha is |3-0| = 3, which is the answer.
Example 2
Input
6 north south north east north south north east
Expected
1
Explanation
east appears only at index 3. north appears at indices 0, 2, and 4. The closest of those to index 3 is index 2 or index 4, giving a distance of |3-2| = 1 (equally |3-4| = 1), so the minimum distance 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 →