Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
nums
?
1 <= nums.length <= 10^4
and k
such that 1 <= k <= nums.length
.nums
?
-10^4 <= nums[i] <= 10^4
.k
frequent elements include ties (i.e., multiple elements having the same frequency)?
k
elements that are most frequent.To solve this problem efficiently, we can use the following steps:
Counter
from the collections
module to tally the frequency of each element in the array.k
elements:
heapq
can help us maintain a heap of size k
to keep track of the most frequent elements.k
most frequent elements by frequency.Let’s implement the solution using these steps:
from collections import Counter
import heapq
def topKFrequent(nums, k):
# Step 1: Count frequency of each element
count = Counter(nums)
# Step 2: Use a heap to extract the k most frequent elements
# Python's heapq is a min-heap
heap = []
for num, freq in count.items():
heapq.heappush(heap, (freq, num)) # Push (frequency, num) tuple
if len(heap) > k:
heapq.heappop(heap) # Ensure the heap keeps only k elements
# Extract the numbers from the heap
result = [num for freq, num in heap]
return result
# Example usage
print(topKFrequent([1,1,1,2,2,3], 2)) # Output: [1, 2]
print(topKFrequent([1], 1)) # Output: [1]
n
is the number of elements in nums
.count
, pushing and popping from the heap takes O(log k) time.
n
elements, heap operations will take O(n log k) time.By efficiently using a frequency count and a min-heap, this approach ensures that we can find the top k
frequent elements within a reasonable time frame even for large input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?