Minimum Number of Pushes to Type Word I (LeetCode 3014): Solution and Explanation
You may remap distinct lowercase letters onto the 8 phone keys 2 to 9, and the kth letter on a key costs k pushes. Return the fewest pushes needed to type word.
Intuition
Every letter in the word is different, so each one is typed exactly once. Which letter goes where does not matter, only how many letters there are.
The keypad offers slots in tiers: 8 slots that cost one push (the first letter on each key), 8 that cost two, 8 that cost three and 2 that cost four.
To pay as little as possible, use every one-push slot before any two-push slot, and so on. The letter at index i lands in tier i // 8, so it costs i // 8 + 1 pushes.
Approach: Fill tiers in order
- Start with
pushes = 0. - For each index i of the word, add
i // 8 + 1. - Return
pushes.
Step-by-step example
word = "abcde"
- Letters a, b, c, d and e take keys 2 to 6 as their first letter.
- Each costs i // 8 + 1 = 1 push.
- The total is 5.
Code: Python, Java, C++
1class Solution:
2 def minimumPushes(self, word: str) -> int:
3 pushes = 0
4 for i in range(len(word)):
5 pushes += i // 8 + 1
6 return pushes1class Solution {
2 public int minimumPushes(String word) {
3 int pushes = 0;
4 for (int i = 0; i < word.length(); i++) {
5 pushes += i / 8 + 1;
6 }
7 return pushes;
8 }
9}1class Solution {
2public:
3 int minimumPushes(string word) {
4 int pushes = 0;
5 for (int i = 0; i < (int)word.size(); i++) {
6 pushes += i / 8 + 1;
7 }
8 return pushes;
9 }
10};Time and space complexity
O(n)
One step per letter, and n is at most 26.
O(1)
Only a running total.
Other approaches
Closed form (time O(1), space O(1))
With q = n // 8 full tiers and r = n % 8 left over, the answer is 8 * q * (q + 1) / 2 + r * (q + 1).
Frequency sort (version II) (time O(n), space O(1))
Counting letters and sorting by frequency also works here, but every frequency is 1, so it reduces to the same sum.
Common mistakes
- Dividing by 9 or 10 instead of 8. Only keys 2 to 9 hold letters.
- Writing i // 8 without the + 1, which makes the first tier free.
- Overthinking which letter goes where: with distinct letters every assignment that fills the cheap tiers first is optimal.
Frequently asked questions
Why does the order of letters not matter?
Each letter is typed exactly once, so swapping two letters between slots does not change the total. Only the set of slots used matters.
What is the largest possible answer?
With all 26 letters: 8 * 1 + 8 * 2 + 8 * 3 + 2 * 4 = 56.
How does version II differ?
In version II letters repeat, so the most frequent letters must go in the cheapest slots. That needs counting and sorting by frequency.