Advertisement

Top K Frequent Elements - LeetCode 347 Solution

Top K Frequent Elements - Complete Solution Guide

Top K Frequent Elements is LeetCode problem 347, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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] Example 3: Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2 Output: [1,2] Constraints: 1 <= nums.length <= 10 5 -10 4 <= nums[i] <= 10 4 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 algori

Detailed Explanation

The problem asks us to find the `k` most frequent elements in a given integer array `nums`. The input includes the array `nums` and an integer `k`. The output should be a list of the `k` most frequent elements. The order of elements in the output list doesn't matter. The constraints state that `k` is always valid (between 1 and the number of unique elements) and the answer is guaranteed to be unique. The follow-up requires an algorithm with time complexity better than O(n log n).

Solution Approach

The provided solutions use a frequency counting approach combined with bucket sort. First, a hash map is used to count the occurrences of each element in the input array. Then, a 'bucket' array (or frequency array) is created. The index of this array represents the frequency, and the values stored at each index are the elements that occur with that frequency. Finally, the code iterates through the frequency array from the highest frequency to the lowest, adding elements to the result list until the list has `k` elements.

Step-by-Step Algorithm

  1. Step 1: Create a hash map (dictionary) to store the frequency of each element in the input array `nums`. Iterate through `nums` and update the frequency count for each element.
  2. Step 2: Create a frequency array (bucket sort). The size of the frequency array is `len(nums) + 1`, where the index represents the frequency and the value is a list of elements with that frequency.
  3. Step 3: Iterate through the hash map created in Step 1 and populate the frequency array. For each element and its frequency, add the element to the list at the corresponding index in the frequency array.
  4. Step 4: Create an empty result list to store the top `k` frequent elements.
  5. Step 5: Iterate through the frequency array from the highest frequency (last index) down to the lowest frequency (index 1). For each frequency, iterate through the list of elements at that frequency and add them to the result list.
  6. Step 6: Check if the size of the result list has reached `k`. If so, return the result list. If not, continue iterating through the frequency array.
  7. Step 7: If the loop finishes without finding `k` elements (unlikely due to the problem constraints), return the elements found so far.

Key Insights

  • Insight 1: Using a hash map (dictionary) is essential to efficiently count the frequency of each element in the array.
  • Insight 2: The follow-up requirement of better than O(n log n) time complexity suggests avoiding sorting-based approaches. Bucket sort (or frequency array) provides O(n) time complexity.
  • Insight 3: The uniqueness guarantee simplifies the problem as we don't have to deal with ties for frequency at the k-th position.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect.

Companies

Asked at: Arista Networks, Atlassian, Avito, ByteDance, Chewy, Cisco, Docusign, DoorDash, Dropbox, EPAM Systems, Goldman Sachs, Hubspot, Intuit, J.P. Morgan, Microstrategy, Netflix, Nutanix, PayPal, Pinterest, Pocket Gems, Robinhood, Roku, Salesforce, Smartsheet, Snap, Snowflake, SoFi, Tesla, Tiger Analytics, Twilio, Visa, Walmart Labs, Yandex, Yelp, eBay.