algorythms
All Patterns
Pattern 19

Heap / Priority Queue

Heap / Priority Queue

A heap gives you O(log n) insert and O(1) peek at the min or max. Essential for "Top K", streaming medians, scheduling, and merging sorted streams.

Time

O(n log k)

Space

O(k)

Recognize it when

  • "Top K largest/smallest/frequent" elements
  • Repeatedly extract the minimum or maximum
  • Merge K sorted arrays or lists
  • Scheduling with priorities (Task Scheduler)
Progress0/11
0 solved0 attempted

Questions — ordered by difficulty

#215Medium

Kth Largest Element in an Array

Find the kth largest element in an unsorted array (not kth distinct).

arrayheapquickselect
#347Medium

Top K Frequent Elements

Return the k most frequent elements. Answer can be in any order. Must be better than O(n log n).

arrayheaphash-map
#973Medium

K Closest Points to Origin

Return the k closest points to the origin (0, 0). Distance is Euclidean.

arrayheapmath
#621Medium

Task Scheduler

Given tasks and a cooldown n, find the minimum time to execute all tasks (same task must wait n intervals between executions).

arrayheapgreedy
#767Medium

Reorganize String

Rearrange characters in a string so no two adjacent characters are the same. Return "" if impossible.

stringheapgreedy
#23Hard

Merge k Sorted Lists

Merge k sorted linked lists into one sorted linked list.

linked-listheapdivide-and-conquer
#146Medium

LRU Cache

Design a data structure that follows LRU (Least Recently Used) cache eviction. Both get and put must be O(1).

designhash-maplinked-list
#295Hard

Find Median from Data Stream

Design a data structure that supports adding numbers and finding the median in O(log n) and O(1) respectively.

heaptwo-heapsdesign
#502Hard

IPO

Maximize capital after completing at most k projects. Each project has a required capital and a profit.

heapgreedysorting
#632Hard

Smallest Range Covering Elements from K Lists

Find the smallest range [a, b] such that at least one element from each of the k sorted lists lies in the range.

heapsliding-windowsorting
#460Hard

LFU Cache

Design and implement a data structure for a Least Frequently Used (LFU) cache.

designhash-maplinked-list