#3016
Minimum Number of Pushes to Type Word II
MediumHash TableStringGreedySortingCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach involves counting the frequency of each letter and distributing them evenly across the available keys. This minimizes the total pushes required by ensuring that no key is overloaded with too many letters.
⚙️
Algorithm
4 steps- 1Step 1: Count the frequency of each letter in the word.
- 2Step 2: Sort the frequencies in descending order.
- 3Step 3: Distribute the letters across the keys, ensuring that the most frequent letters get the least number of pushes.
- 4Step 4: Calculate the total pushes based on the distribution.
solution.py11 lines
1# Full working Python code
2from collections import Counter
3
4def min_pushes_optimal(word):
5 freq = Counter(word)
6 frequencies = sorted(freq.values(), reverse=True)
7 pushes = 0
8 for i, count in enumerate(frequencies):
9 pushes += (i // 8 + 1) * count
10 return pushes
11ℹ
Complexity note: This complexity arises from counting the frequencies (O(n)) and sorting them (O(n log n)). The space is used to store the frequency counts.
- 1Distributing letters evenly across keys minimizes total pushes.
- 2The frequency of letters directly influences the optimal mapping.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.