|
| 1 | +from collections import Counter |
| 2 | +import heapq |
| 3 | + |
| 4 | + |
| 5 | +def minimum_pushes_greedy_with_sorting(word: str) -> int: |
| 6 | + # frequency vector of size 26 that stores the count of each letter in the word |
| 7 | + # Space complexity here is O(1) because we have a constant space for the given list, i.e. 26 |
| 8 | + frequency = [0] * 26 |
| 9 | + |
| 10 | + # Iterate through each character and increment the count in the frequency at the index corresponding to char - "a" |
| 11 | + # since we know from the given constraints that we will have lowercase English letters, this will work fine |
| 12 | + # This is an O(n) operation, as each character in the word is iterated through |
| 13 | + for char in word: |
| 14 | + frequency[ord(char) - ord("a")] += 1 |
| 15 | + |
| 16 | + # Sort the frequencies in descending order to prioritize letters with higher counts |
| 17 | + # O(n log(n)) operation to handle sorting, with a space complexity of O(n) as Python uses in-memory space to handle |
| 18 | + # the sorting using timsort |
| 19 | + frequency.sort(reverse=True) |
| 20 | + |
| 21 | + # total number of key presses required |
| 22 | + total_pushes = 0 |
| 23 | + |
| 24 | + # iterate through the sorted frequency |
| 25 | + for i in range(26): |
| 26 | + # if the frequency of a letter is zero, break the loop as there are no more letters to process |
| 27 | + if frequency[i] == 0: |
| 28 | + break |
| 29 | + # calculate the number of pushes for each letter based on its position in the sorted list (i / 8 + 1) * frequency[i] |
| 30 | + total_pushes += (i // 8 + 1) * frequency[i] |
| 31 | + |
| 32 | + return total_pushes |
| 33 | + |
| 34 | + |
| 35 | +def minimum_pushes_heap(word: str) -> int: |
| 36 | + # frequency_map to store the count of each letter |
| 37 | + frequency_map = Counter(word) |
| 38 | + |
| 39 | + # Priority queue/max heap to store frequencies in descending order |
| 40 | + frequency_queue = [-freq for freq in frequency_map.values()] |
| 41 | + heapq.heapify(frequency_queue) |
| 42 | + |
| 43 | + # total number of key presses required |
| 44 | + total_pushes = 0 |
| 45 | + index = 0 |
| 46 | + |
| 47 | + # iterate through the sorted frequency_map |
| 48 | + while frequency_queue: |
| 49 | + total_pushes += (1 + (index // 8)) * -heapq.heappop(frequency_queue) |
| 50 | + index += 1 |
| 51 | + |
| 52 | + return total_pushes |
0 commit comments