Skip to content

Heap, Intervals & Greedy

PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // smallest on top
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // largest on top
PriorityQueue<int[]> byFirst = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
PriorityQueue<Map.Entry<Integer, Integer>> byValue =
new PriorityQueue<>((a, b) -> b.getValue() - a.getValue()); // OK for small values
pq.offer(x); // O(log n)
pq.poll(); // O(log n), removes the top
pq.peek(); // O(1)
pq.size();

The size-k trick: for the k largest, keep a min-heap of size k. Whenever it grows past k, poll the smallest. What’s left is the top k, and the root is the kth largest. That’s O(n log k).

Problem: Kth Largest Element in an Array (Medium) — LC 215

Approach (say out loud): “Sorting is O(n log n). Better: a min-heap capped at size k. After processing everything, the top is the kth largest. That’s O(n log k). Quickselect gives O(n) on average, which I can mention as a follow-up.”

Java:

class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int x : nums) {
minHeap.offer(x);
if (minHeap.size() > k) minHeap.poll();
}
return minHeap.peek();
}
}

Complexity: O(n log k) time, O(k) space

Edge cases: duplicates count separately ([3,3,2], k=2 → 3), k = 1, k = n.

Problem: K Closest Points to Origin (Medium) — LC 973

Approach (say out loud): “I want the k smallest distances, so I use a max-heap of size k on squared distance (no sqrt needed). If it grows past k, I evict the farthest.”

Java:

class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
(a, b) -> Integer.compare(dist(b), dist(a)));
for (int[] p : points) {
maxHeap.offer(p);
if (maxHeap.size() > k) maxHeap.poll();
}
int[][] res = new int[k][];
for (int i = 0; i < k; i++) res[i] = maxHeap.poll();
return res;
}
private int dist(int[] p) { return p[0] * p[0] + p[1] * p[1]; }
}

Complexity: O(n log k) time, O(k) space

Edge cases: ties (any order is fine), k == n.

Problem: Merge k Sorted Lists (Hard) — LC 23

Approach (say out loud): “Put the head of every list in a min-heap. Poll the smallest, attach it to the result, and push its next node. The heap never holds more than k nodes.”

Java:

class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
for (ListNode head : lists) {
if (head != null) pq.offer(head);
}
ListNode dummy = new ListNode(0), tail = dummy;
while (!pq.isEmpty()) {
ListNode node = pq.poll();
tail.next = node;
tail = node;
if (node.next != null) pq.offer(node.next);
}
return dummy.next;
}
}

Complexity: O(N log k) time, where N = total nodes. O(k) space.

Edge cases: an empty array, lists that contain nulls, all lists empty.

Problem: Find Median from Data Stream (Hard) — LC 295

Approach (say out loud): “Two heaps: a max-heap for the smaller half and a min-heap for the larger half. I keep them balanced, with the small side allowed one extra. The median comes from the tops.”

Java:

class MedianFinder {
private final PriorityQueue<Integer> small = new PriorityQueue<>(Collections.reverseOrder());
private final PriorityQueue<Integer> large = new PriorityQueue<>();
public void addNum(int num) {
small.offer(num);
large.offer(small.poll()); // move the largest of small into large
if (large.size() > small.size()) {
small.offer(large.poll()); // rebalance
}
}
public double findMedian() {
if (small.size() > large.size()) return small.peek();
return (small.peek() + (double) large.peek()) / 2.0;
}
}

Complexity: O(log n) per add, O(1) median, O(n) space

Edge cases: a single element, even vs odd count, negative numbers. The (double) cast avoids integer overflow when summing.

Intervals pattern: sort by start, then compare each interval with the last one you kept. Two intervals [a, b] and [c, d] (with a ≤ c) overlap if c <= b.

Problem: Merge Intervals (Medium) — LC 56

Approach (say out loud): “Sort by start. If the current interval starts at or before the end of the last merged one, they overlap, so I extend the end. Otherwise I start a new merged interval.”

Java:

class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> merged = new ArrayList<>();
for (int[] cur : intervals) {
if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < cur[0]) {
merged.add(cur);
} else {
int[] last = merged.get(merged.size() - 1);
last[1] = Math.max(last[1], cur[1]);
}
}
return merged.toArray(new int[0][]);
}
}

Complexity: O(n log n) time, O(n) space

Edge cases: touching intervals [1,2],[2,3] merge to [1,3], one interval containing another ([1,10],[2,3], hence the Math.max).

Problem: Insert Interval (Medium) — LC 57

Approach (say out loud): “The list is already sorted. Three phases: add every interval that ends before the new one starts, merge every interval that overlaps the new one, then add the rest.”

Java:

class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> res = new ArrayList<>();
int i = 0, n = intervals.length;
while (i < n && intervals[i][1] < newInterval[0]) res.add(intervals[i++]);
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
res.add(newInterval);
while (i < n) res.add(intervals[i++]);
return res.toArray(new int[0][]);
}
}

Complexity: O(n) time, O(n) space

Edge cases: an empty list, the new interval going before everything or after everything, the new interval covering all of them.

Problem: Meeting Rooms I and II (Easy / Medium) — LC 252 / 253

Approach (say out loud): “I: sort by start, and if any meeting starts before the previous one ends, someone can’t attend everything. II, the minimum number of rooms: sort by start and keep a min-heap of end times for rooms in use. If the earliest-ending room frees up before this meeting starts, I reuse it (poll). Then I push this meeting’s end. The heap size is the number of rooms.”

Java:

class Solution {
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < intervals[i - 1][1]) return false;
}
return true;
}
public int minMeetingRooms(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
PriorityQueue<Integer> ends = new PriorityQueue<>();
for (int[] m : intervals) {
if (!ends.isEmpty() && ends.peek() <= m[0]) ends.poll(); // reuse a room
ends.offer(m[1]);
}
return ends.size();
}
}

Complexity: O(n log n) time, O(n) space

Edge cases: a meeting ending exactly when another starts can share the room (<=), an empty list → 0.

Greedy = make the best local choice and never look back. It’s only correct when you can argue that the local choice is safe. In the interview, say why it works: “Taking the earliest-ending interval leaves the most room for the rest.” If you can’t justify it, it’s probably DP.

Problem: Jump Game (Medium) — LC 55

Approach (say out loud): “I track the farthest index I can reach so far. If I’m ever standing at an index beyond that, I’m stuck. If the farthest reach covers the last index, return true.”

Java:

class Solution {
public boolean canJump(int[] nums) {
int farthest = 0;
for (int i = 0; i < nums.length; i++) {
if (i > farthest) return false;
farthest = Math.max(farthest, i + nums[i]);
if (farthest >= nums.length - 1) return true;
}
return true;
}
}

Complexity: O(n) time, O(1) space

Edge cases: a single element → true, a zero at the start [0,1] → false.

Problem: Jump Game II (Medium) — LC 45

Approach (say out loud): “This is BFS by levels in disguise. end is the boundary of the current jump’s reach. While scanning, I track the farthest reach of the next jump. When I hit end, I must jump: count it and set end = farthest.”

Java:

class Solution {
public int jump(int[] nums) {
int jumps = 0, end = 0, farthest = 0;
for (int i = 0; i < nums.length - 1; i++) { // no jump needed from the last index
farthest = Math.max(farthest, i + nums[i]);
if (i == end) {
jumps++;
end = farthest;
}
}
return jumps;
}
}

Complexity: O(n) time, O(1) space

Edge cases: a single element → 0 jumps.

Problem: Non-overlapping Intervals (Medium) — LC 435

Approach (say out loud): “To remove as few as possible, I keep as many as possible. Greedy: sort by end and always keep the interval that ends earliest, because it leaves the most room. Anything that overlaps the last kept interval gets removed.”

Java:

class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int removed = 0, lastEnd = Integer.MIN_VALUE;
for (int[] in : intervals) {
if (in[0] >= lastEnd) lastEnd = in[1]; // keep it
else removed++; // overlaps, so remove it
}
return removed;
}
}

Complexity: O(n log n) time, O(1) extra space

Edge cases: touching intervals [1,2],[2,3] don’t overlap here.