Return the values that appear most frequently in an integer array.
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
kdistinct values fromnums - The values should be the ones with the highest frequencies
Notes
- If multiple valid answers exist, any one of them is acceptable.
- Assume
kis valid and does not exceed the number of distinct elements.
Input Format
nums: integer arrayk: 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 numsnumscontains at least one element- Elements may repeat many times
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.