Skip to main content
All Questions

Top k frequent elements

Medium
Given an array of n numbers and a positive integer K, find the K numbers that appear most frequently in the array. If there is a tie, any set of K numbers can be returned.

Given an integer array nums and an integer k, return the k values that appear most often. You can return them in any order. The answer is guaranteed to be unique.

Example 1

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

1 appears three times and 2 appears twice.

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 in nums.
  • The set of k most frequent values is unique.

Related courses

Course

Data Science Interview Prep

Land your dream data science role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more.

Course

Data Engineering Interview Prep

Land your dream data engineering role at Meta, Google, Amazon, Microsoft, Walmart, DoorDash, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice data modeling, pipeline design, SQL, coding, behavioral interviews, and more.