MediumNo. 2268LeetCode Premium

Minimum Number of Keypresses — LeetCode 2268 Python Solution

Pattern
Greedy
Topics
Greedy, Hash Table, String, Counting, Sorting
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

PythonSolution
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

Time
O(n + |Σ| × log |Σ|)
Space · auxiliary
O(|Σ|)

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

Related problems
No.ProblemDifficulty
0767Reorganize StringMedium
0451Sort Characters By FrequencyMedium
0621Task SchedulerMedium
0692Top K Frequent WordsMedium
1054Distant BarcodesMedium
1090Largest Values From LabelsMedium

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 + |Σ| × log |Σ|).

What is the space complexity of LeetCode 2268. Minimum Number of Keypresses?

The Python solution on this page uses O(|Σ|) 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.

Free to download. Check it runs on your machine, then pick a plan.