ExamAdda Logo

Top K Frequent Elements

Medium

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]

Explanation

The frequencies are:

1 → 3 times
2 → 2 times
3 → 1 time

The two most frequent elements are 1 and 2.

Example 2

Input

nums = [1]
k = 1

Output

[1]

Explanation

There is only one distinct element, so it is the most frequent element.

Constraints

1 <= nums.length <= 100000
1 <= k <= number of distinct elements in nums
-10000 <= nums[i] <= 10000

Hints:

Hint 1

Count the frequency of every element using a hash map.

Hint 2

Use a heap to keep track of the k elements with the highest frequencies.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 26, 2026

Last updated

Aug 26, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output