Asked at
Top K Frequent Elements
MediumVerifiedHash MapHeapSorting~20 min
Given an integer array nums and an integer k, return the k most frequent values.
Count occurrences, then take the k values with the highest counts. Return them in any order.
The input arrives as a single object { nums, k }.
Examples
in{ nums: [1, 1, 1, 2, 2, 3], k: 2 }
out[1, 2]
1 appears 3 times, 2 appears twice — the two most frequent.
in{ nums: [1], k: 1 }
out[1]
Only one value exists.
Constraints
- 1 ≤ nums.length ≤ 10⁵
- 1 ≤ k ≤ number of distinct values
- The k most frequent values are unique.
Get help
🔑
Sign in to solve
Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.