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 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
T9 Keypad Optimization VisualizationInput: "hello"Step 1: Count Frequenciesh: 1, e: 1, l: 2, o: 1Most frequent: 'l' appears 2 timesStep 2: Sort by FrequencySorted: l(2), h(1), e(1), o(1)Assign 'l' to best position firstStep 3: Optimal Keypad AssignmentButton 1l (1 press)Freq: 2Button 2h (1 press)Freq: 1Button 3e (1 press)Freq: 1Button 4o (1 press)Freq: 1Step 4: Calculate Totalh(1×1) + e(1×1) + l(2×1) + o(1×1) = 5 keypresses✓ Optimal assignment achieved!
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!
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen