Top K Elements

Find top K largest, smallest, or most frequent elements using heaps

Algorithm Code

Time: O(n log k) | Space: O(k)

1function topKLargest(nums, k) {
2  const heap = new MinHeap();
3  
4  for (let i = 0; i < nums.length; i++) {
5    if (heap.size() < k) {
6      heap.push(nums[i]);
7    } else if (nums[i] > heap.peek()) {
8      heap.pop();
9      heap.push(nums[i]);
10    }
11  }
12  
13  return heap.toArray().sort((a, b) => b - a);
14}

Algorithm Steps

Step 1 of 14

1

Initialize Min Heap

Create empty min heap to maintain top 3 largest elements.

2

Process arr[0] = 3

Consider element 3 for top 3 largest elements.

3

Add to Heap

Heap size < 3, add 3 to heap.

4

Process arr[1] = 2

Consider element 2 for top 3 largest elements.

5

Add to Heap

Heap size < 3, add 2 to heap.

6

Process arr[2] = 1

Consider element 1 for top 3 largest elements.

7

Add to Heap

Heap size < 3, add 1 to heap.

8

Process arr[3] = 5

Consider element 5 for top 3 largest elements.

9

Replace in Heap

5 > 1 (min in heap), replace 1 with 5.

10

Process arr[4] = 6

Consider element 6 for top 3 largest elements.

11

Replace in Heap

6 > 2 (min in heap), replace 2 with 6.

12

Process arr[5] = 4

Consider element 4 for top 3 largest elements.

13

Replace in Heap

4 > 3 (min in heap), replace 3 with 4.

14

Algorithm Complete ✅

Top 3 largest elements: [6, 5, 4]

Input Array

3
2
1
5
6
4
[0]
[1]
[2]
[3]
[4]
[5]

Min Heap (Size: 0/3)

Empty heap

Top 3 Largest Elements

No results yet
Current
Comparing
Added
Removed
Step 0 of 130%
0.25x4x