Loading content...
Given an integer array and a positive integer k, identify and return the k elements that appear most frequently in the array. The result can be returned in any order, but must contain exactly k distinct elements that have the highest occurrence counts.
When multiple elements share the same frequency, any valid selection among them is acceptable. The problem guarantees that a unique answer exists for the given inputs—meaning there will never be ambiguity at the boundary where choosing different elements with equal frequency could yield different sets of k elements.
Your task is to devise an efficient algorithm that counts element occurrences and extracts the top k elements based on their frequency, optimizing for both time and space complexity.
nums = [1,1,1,2,2,3]
k = 2[1,2]In the array, element 1 appears 3 times, element 2 appears 2 times, and element 3 appears 1 time. The two most frequently occurring elements are 1 (frequency: 3) and 2 (frequency: 2), so we return [1, 2]. The output [2, 1] is equally valid since order does not matter.
nums = [1]
k = 1[1]The array contains only one element (1), which appears exactly once. Since k = 1, we return the single most common element, which is 1.
nums = [1,2,1,2,1,2,3,1,3,2]
k = 2[1,2]Element 1 appears 4 times, element 2 appears 4 times, and element 3 appears 2 times. Both 1 and 2 are tied for the highest frequency. Since k = 2, we return both of them: [1, 2] or [2, 1].
Constraints