Minimum Time to Type Word Using Special Typewriter — LeetCode 1974 Python Solution

EasyGreedyString
Problem
#1974
Pattern
Greedy
Reading time
2 min

The problem

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.

Example

Input
word = "abc"
Output
5
Explanation
The characters are printed as follows:

Python solution

Python
class Solution:
    def minTimeToType(self, word: str) -> int:
        ans, a = len(word), ord("a")
        for c in map(ord, word):
            d = abs(c - a)
            ans += min(d, 26 - d)
            a = c
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1974. Minimum Time to Type Word Using Special Typewriter is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1974. Minimum Time to Type Word Using Special Typewriter?
LeetCode 1974. Minimum Time to Type Word Using Special Typewriter is rated Easy on LeetCode.
What is the time complexity of LeetCode 1974. Minimum Time to Type Word Using Special Typewriter?
The Python solution on this page runs in O(n), where n is the length of the string.
What is the space complexity of LeetCode 1974. Minimum Time to Type Word Using Special Typewriter?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1974. Minimum Time to Type Word Using Special Typewriter cover?
LeetCode 1974. Minimum Time to Type Word Using Special Typewriter is tagged Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview