|
| 1 | +from heapq import heappush, heappop |
| 2 | + |
| 3 | +def top_k_frequent(arr, k): |
| 4 | + |
| 5 | + # Dictionary to save the frequency of each number |
| 6 | + num_frequency_map = {} |
| 7 | + |
| 8 | + # Loop through array, adding all elements to dictionary |
| 9 | + for num in arr: |
| 10 | + num_frequency_map[num] = num_frequency_map.get(num, 0) + 1 |
| 11 | + |
| 12 | + # Initialize min heap |
| 13 | + top_k_elements = [] |
| 14 | + |
| 15 | + for num, frequency in num_frequency_map.items(): |
| 16 | + heappush(top_k_elements, (frequency, num)) |
| 17 | + |
| 18 | + if len(top_k_elements) > k: |
| 19 | + heappop(top_k_elements) |
| 20 | + |
| 21 | + # Create list of top k numbers |
| 22 | + top_numbers = [] |
| 23 | + |
| 24 | + while top_k_elements: |
| 25 | + top_numbers.append(heappop(top_k_elements)[1]) |
| 26 | + |
| 27 | + return top_numbers |
| 28 | + |
| 29 | + |
| 30 | + |
| 31 | +# Time Complexity = O(nlogn) |
| 32 | +# Space Complexity = O(n+k) |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | +############################################################################ |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +# Driver code |
| 41 | +def main(): |
| 42 | + arr = [[1, 3, 5, 12, 11, 12, 11, 12, 5], [1, 3, 5, 14, 18, 14, 5], |
| 43 | + [2, 3, 4, 5, 6, 7, 7], [9, 8, 7, 6, 6, 5, 4, 3, 2, 1], |
| 44 | + [2, 4, 3, 2, 3, 4, 5, 4, 4, 4], [1, 1, 1, 1, 1, 1], [2, 3]] |
| 45 | + k = [3, 2, 1, 1, 3, 1, 2] |
| 46 | + |
| 47 | + for i in range(len(k)): |
| 48 | + print(i+1, ". \t Input: (", arr[i], ", ", k[i], ")", sep="") |
| 49 | + print("\t Top", k[i], "frequent Elements: ", |
| 50 | + top_k_frequent(arr[i], k[i])) |
| 51 | + print("-"*100) |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + main() |
| 55 | + |
| 56 | + |
| 57 | + |
0 commit comments