Minimum Number of Keypresses — LeetCode 2268 Python Solution
- Problem
- #2268
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "apple"
- Output
- 5
- Explanation
- One optimal way to setup your keypad is shown above.
Python solution
class Solution:
def minimumKeypresses(self, s: str) -> int:
cnt = Counter(s)
ans, k = 0, 1
for i, x in enumerate(sorted(cnt.values(), reverse=True), 1):
ans += k * x
if i % 9 == 0:
k += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n + |\Sigma| \times \log |\Sigma|) |
| Space | O(|\Sigma|) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2268. Minimum Number of Keypresses is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2268. Minimum Number of Keypresses?
- LeetCode 2268. Minimum Number of Keypresses is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2268. Minimum Number of Keypresses?
- The Python solution on this page runs in O(n + |\Sigma| \times \log |\Sigma|).
- What is the space complexity of LeetCode 2268. Minimum Number of Keypresses?
- The Python solution on this page uses O(|\Sigma|) auxiliary space.
- What topics does LeetCode 2268. Minimum Number of Keypresses cover?
- LeetCode 2268. Minimum Number of Keypresses is tagged Greedy, Hash Table, String, Counting and Sorting on LeetCode.
- Is LeetCode 2268. Minimum Number of Keypresses a premium problem?
- Yes. LeetCode 2268. Minimum Number of Keypresses is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.