Leetcode 3014. Minimum Number of Pushes to Type Word I
The problem statement for the LeetCode problem “Minimum Number of Pushes to Type Word I-out” reads as follows:
You are given a keyboard similar to an old mobile phone, where each key corresponds to some characters. You need to find the minimum number of pushes required to type out a given word.
The keyboard is described by an array, where each element is a string representing the characters that can be typed using the corresponding key.
You need to implement a function that determines the minimum pushes required.
Let’s make some assumptions based on typical constraints:
Let’s illustrate with an example to make sure we understand the scenario clearly:
Example:
["abc", "def", "ghi"]
"ace"
6
(Explanation: To type “ace”, the keys would be pressed as follows: press key 1 -> ‘a’ (1 time), key 3 -> ‘c’ (3 times), key 2 -> ‘e’ (2 times). Total = 1 + 3 + 2 = 6.)To solve this problem, we can follow these steps:
Here is a possible implementation of the solution in C++:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
int minPushesToTypeWord(vector<string>& keyboard, string word) {
unordered_map<char, int> keyPressMap;
// Create the map for each character's key press count from the keyboard
for (int i = 0; i < keyboard.size(); ++i) {
string keyGroup = keyboard[i];
for (int j = 0; j < keyGroup.size(); ++j) {
keyPressMap[keyGroup[j]] = j + 1;
}
}
// Calculate the total number of key presses required for the word
int totalPushes = 0;
for (char c : word) {
if (keyPressMap.find(c) != keyPressMap.end()) {
totalPushes += keyPressMap[c];
}
}
return totalPushes;
}
int main() {
vector<string> keyboard = {"abc", "def", "ghi"};
string word = "ace";
int result = minPushesToTypeWord(keyboard, word);
cout << "Minimum number of pushes: " << result << endl;
return 0;
}
n
is the number of strings in the keyboard and m
is the average length of the strings.k
is the length of the target word.The overall complexity is O(n * m + k), which should be efficient for reasonable input sizes.
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?