Minimum Number of Pushes to Type Word I (LeetCode 3014): Solution and Explanation

Easy
Math
String
Greedy

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

  1. Start with pushes = 0.
  2. For each index i of the word, add i // 8 + 1.
  3. Return pushes.

Step-by-step example

word = "abcde"
  1. Letters a, b, c, d and e take keys 2 to 6 as their first letter.
  2. Each costs i // 8 + 1 = 1 push.
  3. 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 pushes
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Closed form O(1)
Fill tiers in order O(n)
Frequency sort (version II) O(n)
Time

O(n)

One step per letter, and n is at most 26.

Space

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.