Skip to content

Commit 1f98ef4

Browse files
committed
Time: 146 ms (74.94%), Space: 17.8 MB (8.11%) - LeetHub
1 parent 115379a commit 1f98ef4

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def minimumPushes(self, word: str) -> int:
3+
# Step 1: Count the frequency of each character
4+
freq = Counter(word)
5+
6+
# Step 2: Get the frequencies in a list and sort in descending order
7+
frequencies = sorted(freq.values(), reverse=True)
8+
9+
# Step 3: Priority queue to manage key assignments
10+
# Each key can take up to 9 presses (1 through 9 times)
11+
key_presses = [0] * 8 # Since we have keys 2 through 9 (8 keys)
12+
13+
# Min-heap to keep track of the current minimum press for each key
14+
heap = []
15+
for i in range(8): # Keys from 2 to 9 (index 0 to 7 in the heap)
16+
heapq.heappush(heap, (0, i)) # (total presses for this key, key index)
17+
18+
# Step 4: Assign frequencies to keys
19+
total_presses = 0
20+
for frequency in frequencies:
21+
# Get the key with the current minimum total presses
22+
presses, key = heapq.heappop(heap)
23+
presses += 1
24+
total_presses += presses * frequency
25+
# Increment the press count for this key and push back to heap
26+
heapq.heappush(heap, (presses, key))
27+
28+
return total_presses

0 commit comments

Comments
 (0)