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
Recommendation Algorithm Flow for Minimum Time to Type Word Using Special Typewriter

Solution Approach

Track current position. For each char, compute min distance to target on circular alphabet. Add distance + 1 (typing). Update position.

function solution(word) {
  var pos = 0; // 'a' at index 0
  var total = 0;
  for (var i = 0; i < word.length; i++) {
    var target = word.charCodeAt(i) - 97;
    var diff = Math.abs(target - pos);
    total += Math.min(diff, 26 - diff) + 1;
    pos = target;
  }
  return total;
}

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;
    }
}