Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

15. Top K Frequent Elements

MediumDay 4 of 60Arrays & Hashing

Given an integer array nums and an integer k, return the k values that occur most often. The answer is guaranteed to be unique, and you may return it in any order. Try to beat O(n log n).

Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
1 appears 3 times and 2 appears 2 times, more than any other value.
Example 2
Input: nums = [1], k = 1
Output: [1]
Constraints
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is between 1 and the number of distinct values
  • The top k set is unique
Hints
Frequently asked at: Amazon, Meta, Google, Uber, Oracle
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min