Code Logo

Minimum Time to Type Word Using Special Typewriter

Published at24 Jul 2026
Easy 0 views
Like0

There is a special typewriter with 26 lowercase letters arranged in a circle (a to z). The pointer starts at 'a'. Moving from one letter to another takes 1 second per step clockwise or counterclockwise (minimum distance). Typing a letter takes 1 second. Given a word, return the minimum total time to type it.

This is a state tracking DP problem. The state is the current position on the typewriter (0 for 'a', 1 for 'b', ..., 25 for 'z'). For each character in the word, compute the target position. The cost is the minimum of clockwise and counterclockwise distance plus 1 second to type.

The distance between two positions a and b on a circle of length 26 is min(|a-b|, 26 - |a-b|). The DP iterates through the word, updating the current position after each character.

Time is O(n) with O(1) space. Edge cases include single character, repeated characters (distance 0), and wrapping around 'z' to 'a'.

The typewriter problem uses circular distance: min(|a-b|, 26-|a-b|). The state is the current cursor position, which is updated after each character. This simple DP with a single state variable is O(n) with O(1) space and illustrates how position tracking works in sequential decision problems.

Example Input & Output

Example 1
Input
"aaa"
Output
3
Explanation

Stay at a: 0+1+0+1+0+1 = 3.

Example 2
Input
"abc"
Output
5
Explanation

a:type(1), b:move1+type1=2, c:move1+type1=2. Total=5.

Example 3
Input
""
Output
0
Explanation

No characters.

Example 4
Input
"z"
Output
2
Explanation

Move from a to z: min(25,1)=1 + type1 = 2.

Example 5
Input
"bza"
Output
7
Explanation

a->b:1+1=2, b->z:2+1=3, z->a:1+1=2. Total=7.

Algorithm Flow

Recommendation Algorithm Flow for Minimum Time to Type Word Using Special Typewriter

Solution Approach

Calculate the minimum time to type a word on a circular typewriter where moving to the next/previous letter takes 1 second and pressing takes 1 second. Start at 'a'. For each character, compute the shortest distance to move from the current position, considering both clockwise and counterclockwise directions.

function minTimeToType(word) {
  var time = 0, cur = 'a'.charCodeAt(0);
  for (var i = 0; i < word.length; i++) {
    var target = word.charCodeAt(i);
    var diff = Math.abs(target - cur);
    time += Math.min(diff, 26 - diff) + 1;
    cur = target;
  }
  return time;
}

The circular distance is min(diff, 26 - diff) wrapping around the alphabet. Each character takes movement time plus 1 second to press.

Time O(n), Space O(1).

Best Answers

java
class Solution {
    public int solution(String word) {
        int p=0,t=0;
        for (int i=0;i<word.length();i++) {
            int tg=word.charAt(i)-97;
            int d=Math.abs(tg-p);
            t+=Math.min(d,26-d)+1;
            p=tg;
        }
        return t;
    }
}