Minimum Number of Pushes to Type Word II solution and explanation
9 more videos on this problem
Minimum Number of Pushes to Type Word I and II | Leetcode 3014 | Leetcode 3016 | Weekly ContestcodestorywithMIK · 31:28 · 9K views
Minimum Number of Pushes to Type Word II - Leetcode 3016 - PythonNeetCodeIO · 13:51 · 9K views
3016. Minimum Number of Pushes to Type Word II | Greedy | Word IAryan Mittal · 9:48 · 3K views
LeetCode 3016 - Minimum Number of Pushes to Type Word II - JavaAlpha-Code · 12:17 · 430 views
Daily Leetcode #1589: Aug 06, 2024 - 3016. Minimum Number of Pushes to Type Word IIProgramming Live with Larry · 5:24 · 368 views
3016. Minimum Number of Pushes to Type Word II | Leetcode | C++ - DSATechnosier · 20:18 · 256 views
3016. Minimum Number of Pushes to Type Word II (Leetcode Medium)Programming Live with Larry · 7:17 · 211 views
8/6/24: 3016. Minimum Number of Pushes to Type Word IILeetcodeDailyGrind · 6:21 · 163 views
3016. Minimum Number of Pushes to Type Word I| II Dry Runs | Leetcode| JAVA | C++ || BrogrammersBrogrammers · 29:59 · 140 views
3016. Minimum Number of Pushes to Type Word II | LeetCode POTD | TUTORIAL - 54 | DSA PLAYLISTCoding Kart · 16:17 · 136 views
The problem
You are given a string word containing lowercase English letters.
Telephone keypads have keys mapped with distinct collections of lowercase English letters, which can be used to form words by pushing them. For example, the key 2 is mapped with ["a","b","c"], we need to push the key one time to type "a", two times to type "b", and three times to type "c" .
It is allowed to remap the keys numbered 2 to 9 to distinct collections of letters. The keys can be remapped to any amount of letters, but each letter must be mapped to exactly one key. You need to find the minimum number of times the keys will be pushed to type the string word.
Return the minimum number of pushes needed to type word after remapping the keys.
An example mapping of letters to keys on a telephone keypad is given below. Note that 1, *, #, and 0 do not map to any letters.
Example 1:
Input: word = "abcde" Output: 5 Explanation: The remapped keypad given in the image provides the minimum cost. "a" -> one push on key 2 "b" -> one push on key 3 "c" -> one push on key 4 "d" -> one push on key 5 "e" -> one push on key 6 Total cost is 1 + 1 + 1 + 1 + 1 = 5. It can be shown that no other mapping can provide a lower cost.
Example 2:
Input: word = "xyzxyzxyzxyz" Output: 12 Explanation: The remapped keypad given in the image provides the minimum cost. "x" -> one push on key 2 "y" -> one push on key 3 "z" -> one push on key 4 Total cost is 1 * 4 + 1 * 4 + 1 * 4 = 12 It can be shown that no other mapping can provide a lower cost. Note that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters.
Example 3:
Input: word = "aabbccddeeffgghhiiiiii" Output: 24 Explanation: The remapped keypad given in the image provides the minimum cost. "a" -> one push on key 2 "b" -> one push on key 3 "c" -> one push on key 4 "d" -> one push on key 5 "e" -> one push on key 6 "f" -> one push on key 7 "g" -> one push on key 8 "h" -> two pushes on key 9 "i" -> one push on key 9 Total cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24. It can be shown that no other mapping can provide a lower cost.
Constraints:
1 <= word.length <= 105wordconsists of lowercase English letters.
Approach overview
Problem Overview: You need to type a word using a phone keypad with 8 available keys (2–9). Each key can contain multiple characters, and the number of pushes required equals the character’s position on that key. The goal is to assign letters to keys so the total pushes needed to type the given word is minimized.
Approach 1: Greedy Frequency Mapping (O(n + 26 log 26) time, O(1) space)
Count how often each character appears in the word, then assign the most frequent letters to the cheapest key positions. The keypad effectively has 8 slots that cost 1 push, the next 8 slots cost 2 pushes, the next 8 cost 3 pushes, and the remaining slots cost 4 pushes. After computing character frequencies with a fixed-size array or hash table, sort the frequencies in descending order using sorting. Iterate through the sorted list and multiply each frequency by its push cost using cost = index // 8 + 1. This greedy assignment works because placing higher-frequency characters in cheaper positions minimizes the global total.
This method is optimal since there are only 26 lowercase letters. Sorting at most 26 values is effectively constant time. The algorithm scales linearly with the word length for counting plus a tiny constant overhead for sorting.
Approach 2: Dynamic Key Allocation (O(n + 26 log 26) time, O(1) space)
Another way to model the same idea is to simulate the keypad layout directly. First compute frequencies of all characters using a counting array (a classic counting technique). Sort characters by frequency in descending order. Instead of computing the cost mathematically, dynamically assign characters to keys one by one while tracking how many letters each key currently holds.
Each key accepts characters in layers: the first layer costs 1 push, the second layer costs 2 pushes, and so on. When distributing characters across keys, you fill all 8 keys at push level 1 before moving to push level 2. This allocation mirrors the physical keypad behavior and can be easier to visualize during implementation in languages like C or Java.
Recommended for interviews: The greedy frequency approach is what interviewers expect. It shows you recognize the optimization pattern: prioritize high-frequency elements for the lowest cost slots. Demonstrating the counting step and the index // 8 + 1 cost calculation proves you understand both the greedy reasoning and the keypad constraints.
Approach 1: Greedy Frequency Mapping
Approach: The key idea is to map the most frequently occurring letters to keys such that they require fewer presses. By doing this, we can minimize the total number of key presses needed to type the word. First, count the frequency of each character in the word. Then, sort these characters by frequency in descending order. Assign them to the keys with the least number of lever pulls needed - the key with the highest frequency letters receives only one press.
from collections import Counter
def minimum_presses(word):
frequency = Counter(word)
sorted_frequencies = sorted(frequency.values(), reverse=True)
presses = 0
for i, freq in enumerate(sorted_frequencies):
presses += ((i // 9) + 1) * freq
return presses
# Example usage:
word = "abcde"
print(minimum_presses(word)) # Output: 5function minimumPresses(word) {
let frequency = {};
for (let char of word) {
frequency[char] = (frequency[char] || 0) + 1;
}
let frequencies = Object.values(frequency).sort((a, b) => b - a);
let presses = 0;
for (let i = 0; i < frequencies.length; i++) {
presses += Math.floor(i / 9 + 1) * frequencies[i];
}
return presses;
}
// Example usage:
const word = "abcde";
console.log(minimumPresses(word)); // Output: 5This Python solution uses the Counter class from the collections module to count the frequency of each letter in the word. The frequencies are then sorted in descending order. We process each letter, assigning the most frequent ones to require only one press, using the ((i // 9) + 1) calculation to determine the number of presses for remapped keys.
Time Complexity: O(n + k log k), where n is the length of the word and k is the number of unique letters. Sorting takes O(k log k).
Space Complexity: O(k), where k is the number of unique letters stored in `frequency`.
Approach 2: Dynamic Key Allocation
Approach: Allocate keys dynamically based on frequency but with a twist: instead of pre-sorting all letters, allocate keys to letters in frequency order and determine the number of presses required for each allocation. Keep track of the frequency allocation dynamically using numeric keys to reallocation.
import java.util.Arrays;
public class MinimumPresses {
public static int minimumPushes(String word) {
int[] frequency = new int[26];
for (char c : word.toCharArray()) {
frequency[c - 'a']++;
}
Arrays.sort(frequency);
int presses = 0;
for (int i = 0; i < 26; i++) {
if (frequency[25 - i] > 0) {
presses += ((i / 9) + 1) * frequency[25 - i];
}
}
return presses;
}
public static void main(String[] args) {
String word = "abcde";
System.out.println(minimumPushes(word)); // Output: 5
}
}#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return *(int *)b - *(int *)a;
}
int minimumPushes(char* word) {
int freq[26] = {0};
for (int i = 0; word[i] != '\0'; i++) {
freq[word[i] - 'a']++;
}
qsort(freq, 26, sizeof(int), cmp);
int totalPresses = 0;
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
totalPresses += (i / 9 + 1) * freq[i];
}
}
return totalPresses;
}
// Example usage
int main() {
char word[] = "abcde";
printf("%d\n", minimumPushes(word)); // Outputs: 5
return 0;
}The Java implementation counts each letter’s occurrences and sorts them in ascending order. It then iteratively calculates the minimum key presses needed by incrementally mapping the next highest frequency letter to the optimal, least effort key multiplier positions.
Time Complexity: O(n + k log k), primarily driven by sorting the character frequency array. Here n is the word length, k is a constant 26.
Space Complexity: O(1) extra space required.
Approach 3: Greedy Algorithm + Sorting
We use a hash table or array cnt to count the number of occurrences of each letter in the string word. Next, we sort the letters in descending order of their counts, and then group every 8 letters together, assigning each group to the 8 keys.
The time complexity is O(n + |\Sigma| times log |\Sigma|), and the space complexity is O(|\Sigma|). Here, n is the length of the string word, and \Sigma is the set of letters that appear in the string word.
class Solution {
public:
int minimumPushes(string word) {
vector<int> cnt(26);
for (char& c : word) {
++cnt[c - 'a'];
}
sort(cnt.rbegin(), cnt.rend());
int ans = 0;
for (int i = 0; i < 26; ++i) {
ans += (i / 8 + 1) * cnt[i];
}
return ans;
}
};function minimumPushes(word: string): number {
const cnt: number[] = Array(26).fill(0);
for (const c of word) {
++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)];
}
cnt.sort((a, b) => b - a);
let ans = 0;
for (let i = 0; i < 26; ++i) {
ans += (((i / 8) | 0) + 1) * cnt[i];
}
return ans;
}func minimumPushes(word string) (ans int) {
cnt := make([]int, 26)
for _, c := range word {
cnt[c-'a']++
}
sort.Ints(cnt)
for i := 0; i < 26; i++ {
ans += (i/8 + 1) * cnt[26-i-1]
}
return
}Complexity comparison
| Approach | Complexity |
|---|---|
| Greedy Frequency Mapping | Time Complexity: O(n + k log k), where n is the length of the word and k is the number of unique letters. Sorting takes O(k log k). |
| Dynamic Key Allocation | Time Complexity: O(n + k log k), primarily driven by sorting the character frequency array. Here n is the word length, k is a constant 26. |
| Greedy Algorithm + Sorting | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy Frequency Mapping | O(n + 26 log 26) | O(1) | Best general solution. Simple frequency count followed by greedy assignment. |
| Dynamic Key Allocation | O(n + 26 log 26) | O(1) | Useful when modeling the keypad layout explicitly or implementing step‑by‑step key distribution. |
Frequently asked questions
Is Minimum Number of Pushes to Type Word II easy or hard?
Minimum Number of Pushes to Type Word II is rated Medium difficulty on LeetCode. The implementation is straightforward once you recognize the greedy pattern, but identifying that frequency-based assignment minimizes total cost is the key insight.
Minimum Number of Pushes to Type Word II Python/Java solution
A Python or Java solution typically counts character frequencies, sorts them in descending order, and iterates through the sorted list while computing cost using index // 8 + 1. Each frequency is multiplied by its push cost to accumulate the final minimum total pushes.
How to solve Minimum Number of Pushes to Type Word II in O(n)?
Compute the frequency of each letter in the word using a fixed array of size 26. Sort the frequencies in descending order and assign push costs based on position using the formula index // 8 + 1. Multiply each frequency by its assigned cost and sum the results to get the minimum total pushes.
What is the best approach for Minimum Number of Pushes to Type Word II?
The greedy frequency approach is the most efficient solution. Count how many times each letter appears, sort the frequencies in descending order, and assign the most frequent letters to the cheapest push positions. The first 8 letters cost 1 push, the next 8 cost 2 pushes, and so on. This minimizes the total pushes required to type the word.
Is Minimum Number of Pushes to Type Word II asked at Google/Amazon/Meta?
Greedy frequency optimization problems like this appear frequently in interviews at companies such as Google, Amazon, and Meta. While the exact problem may vary, the pattern of assigning high-frequency elements to low-cost slots is a common interview concept.
What data structure is used in Minimum Number of Pushes to Type Word II?
The main data structures are a frequency array or hash table to count characters and a sorted list of frequencies. The algorithm then uses simple greedy allocation logic to assign push costs.
What is the time complexity of Minimum Number of Pushes to Type Word II?
The time complexity is O(n + 26 log 26), where n is the length of the word. Counting character frequencies takes O(n), and sorting at most 26 values takes O(26 log 26), which is effectively constant. Space complexity is O(1) because the alphabet size is fixed.
