Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Heaps
Amazon
Google
Top K Frequent Elements

Return the kk values that appear most frequently in an integer array.

Acceptance 73%
Problem Statement

Problem

Given an integer array nums and an integer k, return the k elements that occur most often in nums.

The answer can be returned in any order.

This problem focuses on identifying the most frequent values efficiently rather than fully sorting the array by frequency.

Input Format

  • An integer array nums
  • An integer k

Output Format

  • An array containing exactly k distinct values from nums
  • The values should be the ones with the highest frequencies

Notes

  • If multiple valid answers exist, any one of them is acceptable.
  • Assume k is valid and does not exceed the number of distinct elements.

Input Format

  • nums: integer array
  • k: integer

Return the k most frequent distinct elements.

Output Format

  • Integer array of length k
  • Order does not matter

Constraints

  • 1 <= k <= number of distinct values in nums
  • nums contains at least one element
  • Elements may repeat many times
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,1,1,2,2,3], k = 2

Output

[1,2]

Explanation

The frequencies are: 1 -> 3, 2 -> 2, 3 -> 1. The two most frequent elements are 1 and 2.

Example 2

Input

nums = [4,4,4,6,6,1], k = 1

Output

[4]

Explanation

The element 4 appears three times, which is more than any other value.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.