Minimum Time to Type Word Using Special Typewriter

 

1974. Minimum Time to Type Word Using Special Typewriter

There is a special typewriter with lowercase English letters ‘a’ to ‘z’ arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character ‘a’.

Each second, you may perform one of the following operations:

  • Move the pointer one character counterclockwise or clockwise.
  • Type the character the pointer is currently on.
  • Given a string word, return the minimum number of seconds to type out the characters in word.

Solution

  1. Compute the distance between c and pre_c.

  2. Either s or 26-s seconds are needed.

def minTimeToType(self, word: str) -> int:
    pre_c = 'a'
    res = 0
    for c in word:
        ord_c = ord(c)
        ord_pc = ord(pre_c)
        
        s = abs(ord_pc - ord_c)
        res += min(s, 26-s)
            
        pre_c = c
        
    res += len(word)
    return res