Leetcode 1974. Minimum Time to Type Word Using Special Typewriter
You are given a string word
consisting of lowercase English letters. In one second, you can perform one of the following operations:
The pointer initially points to the character ‘a’. Each time a character needs to be typed from word
, you need to move the pointer based on the shortest path (clockwise or counterclockwise) to that character.
Return the minimum number of seconds to type out the entire word.
Is the typewriter circular? Yes, the typewriter is circular, meaning after ‘z’ it wraps around back to ‘a’ and vice versa.
Can the same key be typed more than once?
Yes, each character in the word
needs to be typed in order, regardless of repetitions.
What is the length of the string word
?
The string word
can be up to 100 characters long.
word
.public class MinimumTimeToTypeWord {
public int minTimeToType(String word) {
int totalTime = 0;
char current = 'a';
for (char c : word.toCharArray()) {
int clockwiseDist = Math.abs(c - current);
int counterClockwiseDist = 26 - clockwiseDist;
totalTime += Math.min(clockwiseDist, counterClockwiseDist) + 1;
current = c;
}
return totalTime;
}
public static void main(String[] args) {
MinimumTimeToTypeWord obj = new MinimumTimeToTypeWord();
String word = "cba";
System.out.println("Minimum time to type \"" + word + "\": " + obj.minTimeToType(word));
}
}
The time complexity of this solution is O(n), where n
is the length of the string word
. This is because we are iterating through each character of the string exactly once.
totalTime
to 0 and start at the character ‘a’.word
, we calculate two distances:
Math.abs(c - current)
26 - clockwiseDistance
totalTime
.This approach ensures that we use the minimum time to move between characters and include the time to type each character.
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?