A quality-control scanner arm slides along a single straight rail mounted above a conveyor line. The rail holds exactly 26 fixed slots, numbered 0 through 25 from left to right, and a distinct lowercase-letter label has been bolted into each slot according to a known layout. At the start of the shift the arm is parked directly above slot 0. To read a manifest, the arm must visit the slot holding each label of the manifest in order, one label at a time, sliding along the rail between consecutive visits (including the very first slide, from its starting position at slot 0 to the slot of the first label). Sliding between two slots costs time equal to the absolute difference of their slot numbers. Given the rail's layout and a manifest, find the total time the arm spends sliding to read the entire manifest from start to finish.
layout of exactly 26 lowercase English letters, a permutation of a through z, where layout[i] is the label bolted into slot i (0-indexed).manifest of lowercase English letters — the labels to visit, in order.A single integer: the total sliding time to visit every label of manifest in order, starting from slot 0.
layout has length exactly 26 and is a permutation of a-z.manifest <= 1000manifest consists only of lowercase English letters (each one necessarily appears somewhere in layout, since layout is a permutation of the full alphabet).Example 1
Input
abcdefghijklmnopqrstuvwxyz cba
Expected
4
Explanation
The layout is the identity, so slot i holds letter chr('a'+i). The arm starts at slot 0. It slides to slot 2 for 'c' (cost |2-0|=2), then to slot 1 for 'b' (cost |1-2|=1), then to slot 0 for 'a' (cost |0-1|=1). Total = 2+1+1 = 4.
Example 2
Input
pqrstuvwxyzabcdefghijklmno cargo
Expected
47
Explanation
This layout is the alphabet rotated so slot 0 holds 'p', slot 1 holds 'q', and so on, wrapping so slot 11 holds 'a'. The slot indices of 'c','a','r','g','o' are 13, 11, 2, 17, 25 respectively. Starting at slot 0: to 'c' costs |13-0|=13, to 'a' costs |11-13|=2 (total 15), to 'r' costs |2-11|=9 (total 24), to 'g' costs |17-2|=15 (total 39), to 'o' costs |25-17|=8 (total 47).
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 →