Given a list of integers and a number k, return the k most frequently occurring elements. Elements with higher frequency come first. If multiple elements have the same frequency, order them by value in ascending order. Return an empty list for null or empty input, or when k is null or non-positive.
Examples:
Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]
Explanation: 1 appears 3 times, 2 appears 2 times - these are the top 2
Input: nums = [4, 4, 5, 5, 6], k = 1
Output: [4]
Explanation: 4 and 5 both appear twice, 4 comes first due to lower value
Input: nums = [1], k = 1
Output: [1]
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay October 2026 (Oct 4–15)Sponsored by FLXBL
Contest runs October 4 - 15. Complete challenges to climb the leaderboard!
Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes
Only the 12 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.