An engraving carousel holds a continuous ring of 26 embossing dies, one for each lowercase letter, arranged in alphabetical order around the ring so that 'a' and 'z' sit next to each other. A pointer starts aligned with the die for 'a'. Each second, the operator may either rotate the pointer one die clockwise, rotate it one die counter-clockwise, or press the die currently under the pointer into a blank strip, which stamps that letter and advances the strip to the next position (the pointer itself does not move when pressing). Given a target word, determine the minimum number of seconds needed to stamp out the word's letters onto the strip, in order, starting with the pointer at 'a' and never resetting the pointer between letters.
A single line containing word, a string of 1 to 100 lowercase English letters.
Print a single integer: the minimum total number of seconds required to stamp out word in order.
1 <= |word| <= 100
word consists only of lowercase English letters ('a'-'z').
Example 1
Input
cab
Expected
8
Explanation
Starting at 'a' (position 0): stamping 'c' costs 2 seconds of rotation (a to b to c) plus 1 second to press = 3 (running total 3). Moving from 'c' to 'a' takes 2 steps either direction, so it costs 2 rotation + 1 press = 3 (running total 6). Moving from 'a' to 'b' costs 1 rotation + 1 press = 2 (running total 8).
Example 2
Input
az
Expected
3
Explanation
Stamping 'a' from the starting pointer position costs 0 rotations + 1 press = 1 (running total 1). To reach 'z' from 'a', rotating counter-clockwise 1 step (wrapping past 'a' straight to 'z') is cheaper than rotating clockwise 25 steps, so it costs 1 rotation + 1 press = 2 (running total 3).
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 →