interviewmind

Practice room

Call time 00:00Get the app
D
Dana · Interviewer
You
You
Captions

Press Play and Dana asks the question out loud.

Questions8/17

CodingMedium

Top K Frequent Elements

You’re given an integer array nums and an integer k. Return the k values that appear most often in nums, in any order.

The answer is always unique, so there’s never a tie for the last of the k places. Aim for better than O(n log n) time.

Example 1

Inputnums = [4,4,4,6,6,9], k = 2Output[4,6]

4 appears three times and 6 twice, more than any other value.

Example 2

Inputnums = [7], k = 1Output[7]

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ the number of distinct values in nums
  • The answer is unique

Tab indents. Press Escape, then Tab, to move focus out of the editor.

TypeScriptLn 1, Col 1
Practice room — InterviewMind