Arrays and Hashing Counting and voting

67. Top K Frequent Elements

Medium 147 DSA Sheet

You are given an array of integers nums and an integer k. Return the k different values that appear in nums most often.

The answer is always unique: the input never has a tie for the last place in the answer. You may return the values in any order. The examples list them from smallest to largest.

Example 1

Input: nums = [4, 1, -2, 4, 1, 4, 7, 1, 4], k = 2

Output: [1,4]

Explanation: 4 appears four times and 1 appears three times. -2 and 7 appear once each, so they are not in the answer.

Example 2

Input: nums = [-5, -5, 3, -5, 3, 0], k = 3

Output: [-5,0,3]

Explanation: There are exactly three different values, so all of them are in the answer. Negative values and zero count like any other value.

Example 3

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

Output: [1000000000]

Explanation: Every element is the same value, which appears nums.length times.

Check your understanding

Work out the answer for this input before you write any code.

nums = [8, 8, 2, 5, 5, 5, 9], k = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ the number of different values in nums
  • The k-th most frequent value appears more often than every value outside the answer.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.