Minimum Time to Type Word Using Special Typewriter
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
Stay at a: 0+1+0+1+0+1 = 3.
a:type(1), b:move1+type1=2, c:move1+type1=2. Total=5.
No characters.
Move from a to z: min(25,1)=1 + type1 = 2.
a->b:1+1=2, b->z:2+1=3, z->a:1+1=2. Total=7.
Algorithm Flow

Solution Approach
Track current position. For each char, compute min distance to target on circular alphabet. Add distance + 1 (typing). Update position.
Time O(n), Space O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
