Minimum Number of Keypresses - Problem
Imagine designing the optimal T9 keypad layout! You have a classic phone keypad with 9 buttons (numbered 1-9), and you need to map all 26 lowercase English letters to these buttons to minimize typing effort.
Here are the rules:
• Each button can hold at most 3 characters
• Every letter must be mapped to exactly one button
• To type the 1st character on a button: press 1 time
• To type the 2nd character on a button: press 2 times
• To type the 3rd character on a button: press 3 times
For example, if button 2 has ['a', 'b', 'c'], then typing 'a' costs 1 keypress, 'b' costs 2 keypresses, and 'c' costs 3 keypresses.
Goal: Given a string
Here are the rules:
• Each button can hold at most 3 characters
• Every letter must be mapped to exactly one button
• To type the 1st character on a button: press 1 time
• To type the 2nd character on a button: press 2 times
• To type the 3rd character on a button: press 3 times
For example, if button 2 has ['a', 'b', 'c'], then typing 'a' costs 1 keypress, 'b' costs 2 keypresses, and 'c' costs 3 keypresses.
Goal: Given a string
s, return the minimum total keypresses needed to type the entire string using your optimally designed keypad layout. Input & Output
example_1.py — Basic Case
$
Input:
s = "apple"
›
Output:
5
💡 Note:
Frequency: a(1), p(2), l(1), e(1). Assign 'p' to 1-press position (2×1=2), others to remaining 1-press positions (1×1 each=3). Total: 2+1+1+1=5
example_2.py — All Same Character
$
Input:
s = "aaaaaa"
›
Output:
6
💡 Note:
Only character 'a' appears 6 times. Assign it to a 1-press position. Total keypresses: 6×1 = 6
example_3.py — Many Different Characters
$
Input:
s = "abcdefghijklmnopqrstuvwxyz"
›
Output:
60
💡 Note:
All 26 letters appear once. First 9 get 1-press (9×1=9), next 9 get 2-press (9×2=18), last 8 get 3-press (8×3=24). Total: 9+18+24=51... Wait let me recalculate: 9×1 + 9×2 + 8×3 = 9+18+24=51
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters only
- Key insight: Only 26 letters exist, so sorting is O(26 log 26) = O(1)
Visualization
Tap to expand
Understanding the Visualization
1
Count Usage
Count how frequently each letter appears in your text
2
Rank by Frequency
Sort letters from most used to least used
3
Assign Strategically
Give the easiest positions (1-press) to most frequent letters
4
Calculate Cost
Sum up: frequency × position_cost for each letter
Key Takeaway
🎯 Key Insight: The greedy strategy works perfectly because we want to minimize frequency × cost. Always pair high frequency letters with low cost positions!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code