Skip to main content

Minimum Time to Type Word Using Special Typewriter - Solution & Explanation

EasyStringGreedy16 min readAsked at: IBM, Thomson Reuters, Jpmorgan
Practice this problem

Problem Statement

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.

 

Example 1:

Input: word = "abc"
Output: 5
Explanation: 
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.

Example 2:

Input: word = "bza"
Output: 7
Explanation:
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.

Example 3:

Input: word = "zjpc"
Output: 34
Explanation:
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.

 

Constraints:

  • 1 <= word.length <= 100
  • word consists of lowercase English letters.

Approach Overview

Problem Overview: You start with a pointer on character 'a' of a circular typewriter containing the letters a to z. For each character in the target word, rotate the pointer either clockwise or counterclockwise to reach the letter, then press the key to type it. The goal is to compute the minimum total time required.

Approach 1: Simple Circular Distance Calculation (Greedy) (Time: O(n), Space: O(1))

The alphabet forms a circle of 26 characters. Moving from one letter to another has two possible paths: clockwise and counterclockwise. For each character in the word, compute the distance from the current pointer position using abs(curr - target). The opposite direction distance is 26 - diff. Choose the smaller value and add 1 second for pressing the key. Update the pointer to the typed character and continue scanning the string.

This works because each step is independent. The optimal move between two letters is always the shorter circular distance. No dynamic programming or backtracking is required. The algorithm simply iterates once through the word, making it linear time. This problem mainly tests understanding of circular distance calculations in string problems and applying a straightforward greedy decision at every step.

Approach 2: Prefix Sum Optimization (Time: O(n), Space: O(n))

If multiple distance queries were required, you could precompute cumulative rotation costs using a prefix structure. Convert each character into an index from 0–25 and precompute distances between adjacent characters in the word. A prefix sum array stores cumulative typing cost so that partial ranges can be evaluated quickly. Each transition still uses the same circular distance formula, but prefix sums make it easy to reuse computed movement costs.

For this specific problem the prefix sum approach does not improve asymptotic complexity. The word is processed once and each step is constant work, so the greedy scan is already optimal. Prefix sums mainly demonstrate how repeated movement computations could be aggregated when the problem expands to multiple queries or substring evaluations. It connects with common preprocessing patterns used in string traversal problems.

Recommended for interviews: The greedy circular distance solution is what interviewers expect. It shows you recognized the alphabet is a ring and minimized rotation using min(diff, 26 - diff). Mentioning the prefix-sum idea demonstrates awareness of preprocessing techniques, but the O(n) greedy scan is the clean and optimal implementation.

Approach 1: Simple Circular Distance Calculation

This approach simplifies the problem by calculating the distance between each consecutive character in the word, taking advantage of the circular arrangement. The cost to move the pointer from one character to another is the minimum of the clockwise and counterclockwise distances. The algorithm iterates over the characters of the word, maintaining a total cost variable to track the number of seconds taken.

This C implementation iterates through the word, calculating the minimum distance between the current pointer position and the target character, accounting for both clockwise and counterclockwise directions. Each movement calculation adds the longer of clockwise or counterclockwise paths to the time, plus one second to type the character.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) where n is the length of the word.
Space Complexity: O(1).

Try this approach in the editor →

Approach 2: Prefix Sum Optimization

This approach employs a prefix sum-like optimization, where the traversal through the word strives to minimize the rotational efforts by pre-calculating movement directions and remembering previous movement choices. It considers the word as a sequence of weights, emphasizing preemptive minimization for longer strings where potential repetitive patterns might occur.

In this C solution, the rotation is done by analyzing and comparing costs, summarizing the costs from accumulated calculations. This version seeks to highlight the balance and ensures every previous choice-governed movement cost is recorded succinctly.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) where n is the length of the word.
Space Complexity: O(1).

Try this approach in the editor →

Approach 3: Greedy

We initialize the answer variable ans to the length of the string, indicating that we need at least ans seconds to type the string.

Next, we traverse the string. For each character, we calculate the minimum distance between the current character and the previous character, and add this distance to the answer. Then we update the current character to the previous character and continue traversing.

The time complexity is O(n), where n is the length of the string. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Simple Circular Distance Calculation

Time Complexity: O(n) where n is the length of the word.
Space Complexity: O(1).

Prefix Sum Optimization

Time Complexity: O(n) where n is the length of the word.
Space Complexity: O(1).

Greedy

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Simple Circular Distance Calculation (Greedy)O(n)O(1)Best for the standard problem. Single pass through the word with constant memory.
Prefix Sum OptimizationO(n)O(n)Useful when extending the problem to multiple queries or repeated substring cost calculations.

Video Solution

5834. Minimum Time to Type Word Using Special Typewriter | Leetcode Biweekly Contest 59 | SolutionAbhinav Awasthi926 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Minimum Time to Type Word Using Special Typewriter easy or hard?
This problem is categorized as Easy with a high acceptance rate around 78%. The key idea is recognizing that the alphabet behaves like a circular array and always choosing the shorter rotation direction.
Minimum Time to Type Word Using Special Typewriter Python/Java solution
The implementation iterates through the word, converts characters to indices using ASCII arithmetic, calculates min(diff, 26 - diff), and accumulates the result. The same logic works in Python, Java, C++, C#, and JavaScript with identical O(n) complexity.
How to solve Minimum Time to Type Word Using Special Typewriter in O(n)?
Track the current pointer position starting at 'a'. For each target character, compute the index difference using abs(curr - target). The minimum rotation is min(diff, 26 - diff). Add this rotation time plus one second for typing the character, then update the pointer position.
What is the best approach for Minimum Time to Type Word Using Special Typewriter?
The optimal approach is a greedy circular distance calculation. For each character, compute the clockwise distance and the counterclockwise distance on the 26-letter ring, then choose the smaller one. Add one second for pressing the key. This produces an O(n) time and O(1) space solution.
Is Minimum Time to Type Word Using Special Typewriter asked at Google/Amazon/Meta?
Problems involving circular distance, greedy decisions, and string traversal frequently appear in interviews at companies like Amazon and Google. While this exact question may vary, the underlying pattern of minimizing movement on a circular structure is a common interview concept.
What data structure is used in Minimum Time to Type Word Using Special Typewriter?
The solution mainly uses simple string traversal and integer arithmetic. Characters are converted to numeric indices (0–25) to compute circular distances. No advanced data structures are required, which is why the problem is classified as Easy.
What is the time complexity of Minimum Time to Type Word Using Special Typewriter?
The time complexity is O(n), where n is the length of the word. Each character is processed once and the rotation cost is computed using constant-time arithmetic. Space complexity is O(1) because only the current pointer position and total time are tracked.

Ready to solve this problem?

Practice Minimum Time to Type Word Using Special Typewriter with our built-in code editor and test cases.

Practice on FleetCode