Leetcode 3014. Minimum Number of Pushes to Type Word I Sure! Let’s break down the problem and solve it systematically.
You have a special keyboard with the following keys:
You are initially located at ‘a’ on the keyboard. The cost to move to the next or previous letter in the sequence (circularly) is one push. You need to type a given word (string) using the minimum number of key pushes.
Function signature:
int minPushesToTypeWord(String word)
We’ll iterate through the given word and compute the total minimal pushes required.
public class MinimumPushes {
public static int minPushesToTypeWord(String word) {
int totalPushes = 0;
char currentKey = 'a';
for (int i = 0; i < word.length(); i++) {
char targetKey = word.charAt(i);
totalPushes += minStepsBetween(currentKey, targetKey);
currentKey = targetKey;
}
return totalPushes;
}
private static int minStepsBetween(char from, char to) {
int n = 5; // Given 'a', 'b', 'c', 'd', 'e'
int fromPos = from - 'a'; // Position of 'from' in the sequence
int toPos = to - 'a'; // Position of 'to' in the sequence
return Math.min(Math.abs(toPos - fromPos), n - Math.abs(toPos - fromPos));
}
public static void main(String[] args) {
String word = "cab";
System.out.println(minPushesToTypeWord(word)); // Expected Output: 4
}
}
This solution should be efficient and straightforward for typing the given word using the fewest possible pushes on the special keyboard.
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?