KatInterview

Select K Elements with Highest Occurrence Count

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchhash-mapheapcounting

Last updated

Tests frequency counting with hash maps and efficient selection of top elements using heap-based algorithms.

You are given an array of integers and a positive integer k. Your task is to identify and return the k numbers that appear most frequently in the array.

Each number should appear at most once in your output. The order of numbers in the result does not matter.

Write a function that takes an integer array and returns the k elements with the highest occurrence counts.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= number of distinct elements in nums
  • There is always exactly one valid answer (no ambiguous ties at position k)

Examples

Example 1

Input: select_k_most_frequent([1, 1, 1, 2, 2, 3], 2)

Output: [1, 2]

Example 2

Input: select_k_most_frequent([1], 1)

Output: [1]

Hints

Hint 1

Start by tallying how many times each distinct number appears in the array

Hint 2

You don't need to sort all unique elements—just identify the top k by frequency

Hint 3

Python's heapq module provides efficient functions for finding the largest items without full sorting