DSA Problems/πŸ“ŠArrays & Hashing

Top K Frequent Elements

ArrayHash TableHeapSorting

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.

Approach

Count frequencies with hash map, then use bucket sort or heap to find top k elements.

Complexity Analysis

MetricValue
TimeO(n) with bucket sort
SpaceO(n)

Examples

Example 1

Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Explanation: 1 appears 3 times, 2 appears 2 times

Example 2

Input: nums = [1], k = 1 Output: [1]

Constraints

  • β–Έ1 <= nums.length <= 10^5
  • β–Έ-10^4 <= nums[i] <= 10^4
  • β–Έk is in the range [1, number of unique elements]
Loading...
Sign in to run your code...

Asked by companies:

AmazonFacebookAppleGoogle