Minimum Time to Type Word Using Special Typewriter — LeetCode 1974 Python Solution
- Problem
- #1974
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string |
| Space | O(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.