Skip to content

1974. Minimum Time to Type Word Using Special Typewriter 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int minTimeToType(string word) {
    int moves = 0;
    char letter = 'a';

    for (const char c : word) {
      const int diff = abs(c - letter);
      moves += min(diff, 26 - diff);
      letter = c;
    }

    return moves + word.length();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int minTimeToType(String word) {
    int moves = 0;
    char letter = 'a';

    for (final char c : word.toCharArray()) {
      final int diff = Math.abs(c - letter);
      moves += Math.min(diff, 26 - diff);
      letter = c;
    }

    return moves + word.length();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minTimeToType(self, word: str) -> int:
    moves = 0
    letter = 'a'

    for c in word:
      diff = abs(ord(c) - ord(letter))
      moves += min(diff, 26 - diff)
      letter = c

    return moves + len(word)