Minimum Number of Keypresses - Problem
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 1 button.
- Each button maps to at most 3 characters.
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "abcde"
›
Output:
5
💡 Note:
Each letter appears once. Assign each to position 1 of different buttons: a(1), b(1), c(1), d(1), e(1) = 1+1+1+1+1 = 5 keypresses.
Example 2 — Repeated Letters
$
Input:
s = "aabbcccdddd"
›
Output:
11
💡 Note:
Frequencies: d(4), c(3), a(2), b(2). Assign most frequent to position 1: d(1)×4 + c(1)×3 + a(1)×2 + b(1)×2 = 4+3+2+2 = 11.
Example 3 — Many Unique Letters
$
Input:
s = "abcdefghijk"
›
Output:
13
💡 Note:
11 unique letters, each appears once. First 9 letters get position 1 (9 keypresses), remaining 2 letters get position 2 (2×2=4 keypresses). Total: 9+4=13.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with letter frequencies to optimize
2
Process
Assign frequent letters to require fewer keypresses
3
Output
Minimum total keypresses needed
Key Takeaway
🎯 Key Insight: Assign most frequent letters to positions requiring fewest keypresses
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code