Skip to main content
Back to problems
#1974
Easy Algorithms

Minimum time to type word using special typewriter

String Greedy
78.4% acceptance
Feb 25, 2026
778
38
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

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_time_to_type(word: String) -> i32 {
    let mut time = 0;
    let mut cur = 0i32; // 'a' = 0
    for ch in word.bytes() {
      let target = (ch - b'a') as i32;
      let diff = (target - cur).abs();
      let move_cost = diff.min(26 - diff);
      time += move_cost + 1; // move + type
      cur = target;
    }
    time
  }
}