Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
Constraints:
1 <= nums.length <= 105-104 <= nums[i] <= 104k is in the range [1, the number of unique elements in the array].Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a big pile of items and need to find the ones that appear most often. The brute force approach looks at every single item, counts how many times each one appears overall, and then systematically compares all the counts to find the top winners.
Here's how the algorithm would work step-by-step:
def top_k_frequent(numbers_list, frequency_limit):
frequency_scorecard = {}
# Tally every distinct item to build a complete scorecard of popularity
for current_number in numbers_list:
frequency_scorecard[current_number] = frequency_scorecard.get(current_number, 0) + 1
# Sort the scorecard so the items with the biggest counts rise to the top
sorted_scorecard = sorted(frequency_scorecard.keys(), key=frequency_scorecard.get, reverse=True)
# Read down from the top of the sorted scorecard to pick the requested amount
final_selection = []
for selection_index in range(frequency_limit):
final_selection.append(sorted_scorecard[selection_index])
return final_selectionTo find the most popular items efficiently, we can count how many times each item appears and then group them based on their popularity. Instead of sorting everything, which takes too much time, we can simply place each item into a category corresponding to its exact count and then collect the top ones from the most popular categories.
Here's how the algorithm would work step-by-step:
def top_k_frequent(element_collection, top_count):
frequency_mapping = {}
# Count item frequencies because we need to know how often each element appears.
for current_element in element_collection:
frequency_mapping[current_element] = frequency_mapping.get(current_element, 0) + 1
frequency_buckets = [[] for _ in range(len(element_collection) + 1)]
# Group elements into frequency bins to avoid sorting the entire collection.
for current_element, frequency in frequency_mapping.items():
frequency_buckets[frequency].append(current_element)
result_accumulator = []
# Iterate from highest frequency down to zero to extract the most popular items.
for current_bucket in range(len(frequency_buckets) - 1, 0, -1):
for current_element in frequency_buckets[current_bucket]:
result_accumulator.append(current_element)
if len(result_accumulator) == top_count:
return result_accumulator
return result_accumulator| Case | How to Handle |
|---|---|
| k equals the number of unique elements in the array | The algorithm should return all unique elements since every element meets the frequency threshold. |
| Array contains negative numbers, zeros, and positive numbers | Using a hash map for frequency counting naturally accommodates any integer keys regardless of sign. |
| All elements in the array are identical | The hash map will store a single key with a count equal to the array length, and that key will be returned. |
| All elements in the array are completely unique | Every element has a frequency of one, and any arbitrary subset of size k can be safely returned. |
| Extremely large input arrays causing memory or time limits | An O(N) bucket sort or O(N log k) heap approach ensures efficient scaling without exceeding time limits. |
| Multiple elements share the exact same frequency | The problem specifies that the answer can be returned in any order, so any subset of elements tied at the frequency boundary is acceptable. |
| Array with a single element and k equals one | The frequency map records a count of one for that single element, which is then correctly returned in the result list. |