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
Minimum Number of Keypresses INPUT String s = "abcde" a b c d e Character Frequency a: 1, b: 1, c: 1 d: 1, e: 1 9-Button Keypad 1 2 3 4 5 6 Each button maps up to 3 chars ALGORITHM STEPS 1 Count Frequencies Count each char occurrence 2 Sort by Frequency Descending order (greedy) 3 Assign to Buttons First 9 chars: 1 press each Next 9: 2 presses each Last 8: 3 presses each 4 Calculate Total Sum: freq * presses needed For s = "abcde": All 5 chars have freq = 1 Assign to first positions Each needs 1 press only Total = 1+1+1+1+1 = 5 FINAL RESULT Optimal Button Mapping: 1 a 2 b 3 c 4 d 5 e 6 ... Keypresses for "abcde": 'a' on btn 1: 1 press 'b' on btn 2: 1 press 'c' on btn 3: 1 press 'd' on btn 4: 1 press 'e' on btn 5: 1 press Output: 5 OK - Minimum achieved! Key Insight: Greedy approach: Assign most frequent characters to positions requiring fewer presses. First 9 chars (1 press) --> Next 9 chars (2 presses) --> Last 8 chars (3 presses). TutorialsPoint - Minimum Number of Keypresses | Greedy Approach
Asked in
Google 25 Meta 20 Amazon 15
23.8K Views
Medium Frequency
~15 min Avg. Time
850 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