#2268
Medium Algorithms Minimum number of keypresses
Hash Table String Greedy Sorting Counting
71.5% acceptance
Mar 31, 2026
250
40
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_keypresses(s: String) -> i32 {
let mut freq = [0i32; 26];
for b in s.bytes() {
freq[(b - b'a') as usize] += 1;
}
freq.sort_unstable_by(|a, b| b.cmp(a));
let mut total = 0;
for (i, &f) in freq.iter().enumerate() {
if f == 0 { break; }
total += f * (i as i32 / 9 + 1);
}
total
}
}