Taro Logo

Top K Frequent Elements

#1 Most AskedMedium
73 views
Topics:
ArraysGreedy Algorithms

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] <= 104
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

Solution


Clarifying Questions

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:

  1. Can the input array contain negative numbers, zeros, or is it strictly positive integers?
  2. What should we return if $k$ is greater than the number of unique elements in the array?
  3. If there is a tie in frequency between multiple elements, does the order in the output matter, or can I return any valid combination of the top $k$ elements?
  4. Can $k$ ever be less than 1, or is $k$ guaranteed to be between 1 and the number of unique elements?
  5. Should the returned array of top $k$ elements contain unique values, or can duplicates be present in the result?

Brute Force Solution

Approach

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:

  1. Start by going through your entire collection of items one by one.
  2. For every distinct item you encounter, count how many times it shows up in the entire collection.
  3. Write down every item along with its total count so you have a complete scorecard of popularity.
  4. Sort your scorecard by looking at the counts so the items with the biggest numbers are placed at the very top.
  5. Read down from the top of your sorted scorecard and pick the requested amount of items.
  6. Gather those selected items together as your final answer.

Code Implementation

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_selection

Big(O) Analysis

Time Complexity
O(n log n) – Step 1 through 3 involve iterating through the entire collection of n elements to build a frequency map, which takes O(n) time. Step 4 requires sorting the distinct scorecard of items, taking at most O(n log n) time where n represents the number of unique elements. Steps 5 and 6 take O(k) time to extract the top k elements. As the sorting step dominates the overall process, the total operations approximate n log n, which simplifies to O(n log n).
Space Complexity
O(N) – To execute the steps outlined, we must use a hash map to build the complete scorecard, storing every distinct item and its frequency alongside a temporary list to hold the sorted results. In the worst-case scenario where all elements are unique, the hash map and intermediate structures will store N items, where N is the total number of elements in the collection. Consequently, the auxiliary memory scales linearly with the input size, leading to a space complexity of O(N).

Optimal Solution

Approach

To 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:

  1. Count the total number of times every item appears in the collection.
  2. Create a series of organized bins where each bin represents a specific number of appearances, ranging from a single appearance up to the maximum possible appearances.
  3. Place each item into the bin that matches its exact count of appearances.
  4. Start from the bin representing the highest number of appearances and collect the items found inside.
  5. Continue moving down to the next highest bins, gathering items until you have collected the requested top amount.
  6. Return the final collection of gathered items.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – First, we iterate through the input collection of size n to count the frequency of each element and store them in a hash map, taking O(n) time. Next, we populate an array of buckets where the index represents the frequency, which also takes O(n) time since there are at most n unique elements. Finally, we iterate backward through these buckets from the highest frequency down to the lowest to collect the top k elements, taking at most O(n) time as we visit each bucket and element at most once. Combining these linear passes results in approximately n + n + n operations, which simplifies to O(n).
Space Complexity
O(n) – To analyze the auxiliary space complexity where N is the total number of elements in the input, we must account for the additional data structures created during execution. First, a hash map is used to store the frequency count of each unique element, which requires space proportional to the number of distinct elements, bounded by N. Second, the bucket array contains N plus one lists to group items by their exact frequencies. Finally, the resulting collection of top K elements requires space proportional to K. Combining these structures, the total extra memory grows linearly with the input size N, simplifying to Big O of N.

Edge Cases

k equals the number of unique elements in the array
How to Handle:
The algorithm should return all unique elements since every element meets the frequency threshold.
Array contains negative numbers, zeros, and positive numbers
How to Handle:
Using a hash map for frequency counting naturally accommodates any integer keys regardless of sign.
All elements in the array are identical
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The frequency map records a count of one for that single element, which is then correctly returned in the result list.
0/6 completed