Minimum Number of Keypresses — LeetCode 2268 Python Solution

MediumLeetCode PremiumGreedyHash TableStringCountingSorting
Problem
#2268
Pattern
Greedy
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n + |\Sigma| \times \log |\Sigma|)
SpaceO(|\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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview