#3014
Minimum Number of Pushes to Type Word I
EasyMathStringGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach involves evenly distributing the letters across the keys to minimize the number of pushes. Since we have 8 keys, we can assign letters in groups to achieve the least number of total pushes.
⚙️
Algorithm
3 steps- 1Step 1: Count the number of letters in the word.
- 2Step 2: Calculate how many full groups of 8 can be formed and how many letters will remain.
- 3Step 3: Calculate the total pushes based on the number of groups and remaining letters.
solution.py9 lines
1# Full working Python code
2
3def min_pushes_optimal(word):
4 n = len(word)
5 full_groups = n // 8
6 remaining = n % 8
7 pushes = (full_groups * 8 * (8 + 1)) // 2 + remaining * (full_groups + 1)
8 return pushes
9ℹ
Complexity note: This complexity is linear because we only need to calculate the number of letters and perform a constant amount of arithmetic operations.
- 1Even distribution of letters minimizes pushes.
- 2Each key can handle 8 letters optimally.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.