Leetcode 1974. Minimum Time to Type Word Using Special Typewriter
LeetCode problem 1974: “Minimum Time to Type Word Using Special Typewriter”
There is a special typewriter with a single row of 26 lowercase English letters from ‘a’ to ‘z’. Initially, the pointer is at the letter ‘a’. The typewriter has two special functions:
Given a string word
, return the minimum time to type the entire string. The time to move one slot to the left or right is 1, and the time to type a character is also 1.
word
?
1 <= word.length <= 100
.word
, calculate the shortest distance the pointer must move to reach the target character.#include <iostream>
#include <string>
#include <algorithm>
int minTimeToType(std::string word) {
int totalTime = 0;
char currentPos = 'a';
for (char c : word) {
int clockwiseDist = abs(c - currentPos);
int counterClockwiseDist = 26 - clockwiseDist;
totalTime += std::min(clockwiseDist, counterClockwiseDist) + 1;
currentPos = c;
}
return totalTime;
}
int main() {
std::string word = "cba";
std::cout << "Minimum time to type word \"" << word << "\": " << minTimeToType(word) << " units." << std::endl;
return 0;
}
n
is the length of the word. We iterate through each character in the word exactly once.This solution efficiently calculates the minimum time required to type the given word using a single-row typewriter by evaluating both clockwise and counterclockwise distances and selecting the minimum at each step.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?