An old telephone switchboard has 26 slots arranged in a single row, numbered 0 to 25 from left to right. A layout string assigns each of the 26 lowercase letters to exactly one slot: the letter at position i of the layout string occupies slot i. An operator wants to key in a lowercase word by moving one finger across the slots, pressing the slot for each letter of the word in order. The finger starts resting at slot 0 before the first letter is pressed. Moving the finger from a slot at position p to a slot at position q costs |p - q| units of time, and the finger must visit slots in the exact order needed to spell the word (one slot press per character, including repeats).
Given the layout and the word, compute the total time needed to key in the entire word.
Line 1: the layout string — exactly 26 lowercase letters, a permutation of a-z.
Line 2: the word — a non-empty string of lowercase letters.
A single integer: the total time to key in the word.
Example 1
Input
abcdefghijklmnopqrstuvwxyz cba
Expected
4
Explanation
The layout is the identity, so letter x sits at slot x-'a'. Finger starts at slot 0. Pressing 'c' (slot 2) costs |2-0|=2 (total 2, finger now at 2). Pressing 'b' (slot 1) costs |1-2|=1 (total 3, finger now at 1). Pressing 'a' (slot 0) costs |0-1|=1 (total 4). Answer: 4.
Example 2
Input
bacdefghijklmnopqrstuvwxyz aabb
Expected
2
Explanation
Only 'a' and 'b' are swapped from identity: 'a' is at slot 1 and 'b' is at slot 0. Finger starts at slot 0. Press 'a' (slot 1): cost 1 (total 1, finger at 1). Press 'a' (slot 1): cost 0 (total 1). Press 'b' (slot 0): cost 1 (total 2, finger at 0). Press 'b' (slot 0): cost 0 (total 2). Answer: 2.
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 →