Back to LeetCode solutions

347. Top K Frequent Elements

HashMapSortingArray
3 min read

Problem

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Explanation

My approach: HashMap and stream sorting

I solve this by first counting how many times each number appears, then sorting by frequency to pick the top k. I use a HashMap called repeatedNums to track each number and its count. As I iterate through the array, if a number already exists in the map, I increment its count; otherwise, I add it with a count of 1. Once I have all the frequencies, I convert the map to a stream, sort it by value in descending order (most frequent first), and collect it back into a LinkedHashMap to preserve the sorted order. Finally, I iterate through the sorted map's keys, copying the first k elements into my result array. This approach is straightforward and readable, using Java streams to handle the sorting elegantly.

Time: O(n log n) due to sorting the map entries
Space: O(n) for the HashMap and sorted map

Solution

Java
Tests
Input
nums = [1,1,1,2,2,3], k = 2
Output
(waiting for execution)
Expected Output
1,2