Minimum Number of Keypresses Problem
Description
LeetCode Problem 2268.
You have a keypad with 9 buttons, numbered from 1 to 9, each mapped to lowercase English letters. You can choose which characters each button is matched to as long as:
- All 26 lowercase English letters are mapped to.
- Each character is mapped to by exactly
1button. - Each button maps to at most
3characters.
To type the first character matched to a button, you press the button once. To type the second character, you press the button twice, and so on.
Given a string s, return the minimum number of keypresses needed to type s using your keypad.
Note that the characters mapped to by each button, and the order they are mapped in cannot be changed.
Example 1:

Input: s = "apple"
Output: 5
Explanation: One optimal way to setup your keypad is shown above.
Type 'a' by pressing button 1 once.
Type 'p' by pressing button 6 once.
Type 'p' by pressing button 6 once.
Type 'l' by pressing button 5 once.
Type 'e' by pressing button 3 once.
A total of 5 button presses are needed, so return 5.
Example 2:

Input: s = "abcdefghijkl"
Output: 15
Explanation: One optimal way to setup your keypad is shown above.
The letters 'a' to 'i' can each be typed by pressing a button once.
Type 'j' by pressing button 1 twice.
Type 'k' by pressing button 2 twice.
Type 'l' by pressing button 3 twice.
A total of 15 button presses are needed, so return 15.
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters.
Solution
Approach: Counting + Greedy
Count how often each letter occurs. A letter in the first position of its key costs 1 press per occurrence, in the second position 2, and in the third 3. There are 9 keys, so the 9 most frequent letters should take first positions, the next 9 second positions, and the rest third positions.
Sort the counts in descending order and add k * cnt[i] for each, where k starts at 1 and increases after every 9 letters.
Complexity: time O(n + 26 log 26), space O(26), where n is the length of s.
from collections import Counter
class Solution:
def minimumKeypresses(self, s: str) -> int:
cnt = Counter(s)
ans, k = 0, 1
for i, x in enumerate(sorted(cnt.values(), reverse=True), 1):
ans += k * x
if i % 9 == 0:
k += 1
return ans