Add heap module: array min/max heap with dry runs and bottom-up heapify, PriorityQueue comparators and traps, heap sort, 10 interview problems with brute-force cross-checks (17 tests, 23 transcripts)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4HkWoC7hLzk61vZa8
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
Min-heap: offer [35, 20, 50, 10, 40, 5] one at a time
|
||||
=====================================================
|
||||
|
||||
offer(35) placed at index 0 [35]
|
||||
reached the root [35]
|
||||
offer(20) placed at index 1 [35, 20]
|
||||
parent a[0]=35 > 20 swap 1 <-> 0
|
||||
reached the root [20, 35]
|
||||
offer(50) placed at index 2 [20, 35, 50]
|
||||
parent a[0]=20 <= 50 stop
|
||||
offer(10) placed at index 3 [20, 35, 50, 10]
|
||||
parent a[1]=35 > 10 swap 3 <-> 1
|
||||
parent a[0]=20 > 10 swap 1 <-> 0
|
||||
reached the root [10, 20, 50, 35]
|
||||
offer(40) placed at index 4 [10, 20, 50, 35, 40]
|
||||
parent a[1]=20 <= 40 stop
|
||||
offer(5) placed at index 5 [10, 20, 50, 35, 40, 5]
|
||||
parent a[2]=50 > 5 swap 5 <-> 2
|
||||
parent a[0]=10 > 5 swap 2 <-> 0
|
||||
reached the root [5, 20, 10, 35, 40, 50]
|
||||
|
||||
final array : [5, 20, 10, 35, 40, 50]
|
||||
java.util.PriorityQueue shows: [5, 20, 10, 35, 40, 50]
|
||||
@@ -0,0 +1,13 @@
|
||||
Min-heap: two poll() calls on [5, 20, 10, 35, 40, 50]
|
||||
=====================================================
|
||||
|
||||
poll() returns 5; last value moved to root [50, 20, 10, 35, 40]
|
||||
smaller child a[2]=10 < 50 swap 0 <-> 2
|
||||
reached a leaf [10, 20, 50, 35, 40]
|
||||
poll() returns 10; last value moved to root [40, 20, 50, 35]
|
||||
smaller child a[1]=20 < 40 swap 0 <-> 1
|
||||
smaller child a[3]=35 < 40 swap 1 <-> 3
|
||||
reached a leaf [20, 35, 50, 40]
|
||||
|
||||
final array : [20, 35, 50, 40]
|
||||
java.util.PriorityQueue shows: [20, 35, 50, 40]
|
||||
@@ -0,0 +1,7 @@
|
||||
My heaps vs java.util.PriorityQueue (seed 7)
|
||||
============================================
|
||||
|
||||
random offer/poll operations compared : 100000
|
||||
backing array identical after every one: IntMinHeap, BinaryHeap and PriorityQueue
|
||||
bottom-up builds compared : 500
|
||||
BinaryHeap.heapify(list) and new PriorityQueue<>(list) produced the same array every time
|
||||
@@ -0,0 +1,7 @@
|
||||
Building a min-heap of n = 1,000,000 keys: comparisons
|
||||
======================================================
|
||||
|
||||
input my offer() x n my heapify PriorityQueue.addAll new PriorityQueue(list)
|
||||
random 2,279,262 1,881,044 2,279,262 1,881,044
|
||||
ascending 999,999 999,999 999,999 999,999
|
||||
descending 17,951,445 1,999,974 17,951,445 1,999,974
|
||||
@@ -0,0 +1,9 @@
|
||||
One call on a PriorityQueue of 1,000,000 elements
|
||||
=================================================
|
||||
|
||||
call compareTo equals
|
||||
peek() 0 0
|
||||
offer(new smallest) 19 0
|
||||
poll() 37 0
|
||||
contains(absent) 0 1,000,000
|
||||
remove(absent) 0 1,000,000
|
||||
@@ -0,0 +1,15 @@
|
||||
PriorityQueueTour.run()
|
||||
=======================
|
||||
|
||||
min.peek() = 5
|
||||
max.peek() = 50
|
||||
min drained = [5, 10, 20, 35, 40, 50]
|
||||
max drained = [50, 40, 35, 20, 10, 5]
|
||||
poll -> deploy (priority 5, 15 min)
|
||||
poll -> fix-prod-bug (priority 5, 90 min)
|
||||
poll -> code-review (priority 3, 30 min)
|
||||
poll -> reply-email (priority 2, 5 min)
|
||||
poll -> write-report (priority 2, 60 min)
|
||||
empty.peek() = null
|
||||
empty.poll() = null
|
||||
empty.element() throws NoSuchElementException
|
||||
@@ -0,0 +1,10 @@
|
||||
new PriorityQueue<>(List.of(35, 20, 50, 10, 40, 5))
|
||||
===================================================
|
||||
|
||||
built by add() x 6 : [5, 20, 10, 35, 40, 50]
|
||||
toString() : [5, 10, 35, 20, 40, 50]
|
||||
for-each : [5, 10, 35, 20, 40, 50]
|
||||
stream().toList() : [5, 10, 35, 20, 40, 50]
|
||||
sorted toArray() : [5, 10, 20, 35, 40, 50]
|
||||
stream().sorted() : [5, 10, 20, 35, 40, 50]
|
||||
repeated poll() : [5, 10, 20, 35, 40, 50] (size is now 0)
|
||||
@@ -0,0 +1,8 @@
|
||||
Comparators written with subtraction
|
||||
====================================
|
||||
|
||||
input : [1, -2147483648, 100]
|
||||
(x, y) -> x - y head : 1
|
||||
Integer::compare head : -2147483648
|
||||
1 - Integer.MIN_VALUE = -2147483647 (negative, so 1 'sorts before' MIN_VALUE)
|
||||
(x, y) -> y - x max-heap of [MIN_VALUE, 7], head: -2147483648
|
||||
@@ -0,0 +1,9 @@
|
||||
Mutating a queued element, and equal priorities
|
||||
===============================================
|
||||
|
||||
after c.cost = 1, peek() : A:10
|
||||
polled in order : A:10, C:1, B:20
|
||||
remove, change, add, polled : C:1, A:10, B:20
|
||||
|
||||
equal priority, comparator on priority only : [first, fifth, fourth, third, second]
|
||||
with a sequence number as the tie-breaker : [first, second, third, fourth, fifth]
|
||||
@@ -0,0 +1,7 @@
|
||||
Calls PriorityQueue rejects
|
||||
===========================
|
||||
|
||||
add(null) : NullPointerException
|
||||
add(new Object()) to an empty queue : ClassCastException
|
||||
new PriorityQueue<>(0) : IllegalArgumentException
|
||||
add while iterating : ConcurrentModificationException
|
||||
@@ -0,0 +1,12 @@
|
||||
Heap sort of [35, 20, 50, 10, 40, 5]
|
||||
====================================
|
||||
|
||||
after phase 1 (max-heap) : [50, 40, 35, 10, 20, 5]
|
||||
heap [40, 20, 35, 10, 5] | sorted [50]
|
||||
heap [35, 20, 5, 10] | sorted [40, 50]
|
||||
heap [20, 10, 5] | sorted [35, 40, 50]
|
||||
heap [10, 5] | sorted [20, 35, 40, 50]
|
||||
heap [5] | sorted [10, 20, 35, 40, 50]
|
||||
result : [5, 10, 20, 35, 40, 50]
|
||||
|
||||
random arrays (seed 11) compared with Arrays.sort : 20000, disagreements: 0
|
||||
@@ -0,0 +1,7 @@
|
||||
Comparisons to sort n = 100,000 Integers
|
||||
========================================
|
||||
|
||||
input HeapSort Arrays.sort (TimSort)
|
||||
random 3,020,038 1,534,840
|
||||
ascending 3,112,517 99,999
|
||||
descending 2,926,640 99,999
|
||||
@@ -0,0 +1,6 @@
|
||||
Sort by marks only; names were inserted in alphabetical order
|
||||
=============================================================
|
||||
|
||||
input : [Asha:70, Bala:90, Chitra:70, Dev:90, Esha:70]
|
||||
HeapSort : [Esha:70, Chitra:70, Asha:70, Dev:90, Bala:90]
|
||||
Arrays.sort : [Asha:70, Chitra:70, Esha:70, Bala:90, Dev:90]
|
||||
@@ -0,0 +1,7 @@
|
||||
Problem 1 and 2: k-th largest
|
||||
=============================
|
||||
|
||||
array [3, 2, 3, 1, 2, 4, 5, 5, 6] k = 4 -> 4
|
||||
|
||||
stream, k = 3, starting with [4, 5, 8, 2]:
|
||||
add(3)=4 add(5)=5 add(10)=5 add(9)=8 add(4)=8
|
||||
@@ -0,0 +1,13 @@
|
||||
The k largest of n = 1,000,000 distinct ints: comparisons
|
||||
=========================================================
|
||||
|
||||
input k sort everything min-heap of size k max-heap all, poll k
|
||||
random 10 18,641,233 1,000,758 1,882,132
|
||||
ascending 10 999,999 6,937,439 2,000,353
|
||||
descending 10 999,999 1,000,009 1,000,379
|
||||
random 1,000 18,641,233 1,131,903 1,919,594
|
||||
ascending 1,000 999,999 19,934,399 2,037,781
|
||||
descending 1,000 999,999 1,006,987 1,037,851
|
||||
random 500,000 18,641,233 14,144,364 20,315,500
|
||||
ascending 500,000 999,999 19,451,423 20,856,134
|
||||
descending 500,000 999,999 8,975,732 19,421,238
|
||||
@@ -0,0 +1,10 @@
|
||||
Problem 3: top k frequent
|
||||
=========================
|
||||
|
||||
nums [1, 1, 1, 2, 2, 3, 4, 4, 4, 4] k = 2
|
||||
heap : [4, 1]
|
||||
buckets : [4, 1]
|
||||
|
||||
words [java, heap, queue, java, heap, tree, queue, array] k = 2 (java, heap and queue all occur twice)
|
||||
tie-break reversed inside the worst-first heap : [heap, java]
|
||||
tie-break NOT reversed (the bug) : [queue, java]
|
||||
@@ -0,0 +1,8 @@
|
||||
Problem 4 and 5
|
||||
===============
|
||||
|
||||
points [3,3] [5,-1] [-2,4], k = 2 -> [[-2, 4], [3, 3]]
|
||||
point (50000, 0): squared distance in int = -1794967296
|
||||
point (50000, 0): squared distance in long = 2500000000
|
||||
|
||||
stones [2, 7, 4, 1, 8, 1] -> last stone weight 1
|
||||
@@ -0,0 +1,12 @@
|
||||
Problem 6: merge k sorted lists
|
||||
===============================
|
||||
|
||||
[1,4,5] [1,3,4] [2,6] [] -> [1, 1, 2, 3, 4, 4, 5, 6]
|
||||
offering the head of an empty list (null) without the check: NullPointerException
|
||||
|
||||
comparisons, each list holding 1,000 random values (seed 5):
|
||||
k N heap of heads merge one by one merge in pairs
|
||||
2 2,000 1,998 1,998 1,998
|
||||
10 10,000 61,857 53,944 35,983
|
||||
100 100,000 1,270,358 5,045,132 687,813
|
||||
1,000 1,000,000 18,739,107 500,034,011 9,982,020
|
||||
@@ -0,0 +1,13 @@
|
||||
Problem 7: median of a stream
|
||||
=============================
|
||||
|
||||
add( 5) lower(max-heap)=[5] upper(min-heap)=[] median=5.0
|
||||
add(15) lower(max-heap)=[5] upper(min-heap)=[15] median=10.0
|
||||
add( 1) lower(max-heap)=[1, 5] upper(min-heap)=[15] median=5.0
|
||||
add( 3) lower(max-heap)=[1, 3] upper(min-heap)=[5, 15] median=4.0
|
||||
add( 8) lower(max-heap)=[1, 3, 5] upper(min-heap)=[8, 15] median=5.0
|
||||
add( 7) lower(max-heap)=[1, 3, 5] upper(min-heap)=[7, 8, 15] median=6.0
|
||||
|
||||
values 2147483647 and 2147483645:
|
||||
(a + b) / 2.0 in int arithmetic : -2.0
|
||||
((long) a + b) / 2.0 : 2147483646.0
|
||||
@@ -0,0 +1,7 @@
|
||||
Problem 8: task scheduler ('.' = idle)
|
||||
======================================
|
||||
|
||||
tasks=AAABBB n=2 timeline=AB.AB.AB length=8 formula=8
|
||||
tasks=AAABBB n=0 timeline=ABABAB length=6 formula=6
|
||||
tasks=AAAAAABCDEFG n=2 timeline=ABCADEAFGA..A..A length=16 formula=16
|
||||
tasks=AAABBBCCCDD n=2 timeline=ABCABCDABCD length=11 formula=11
|
||||
@@ -0,0 +1,8 @@
|
||||
Problem 9 and 10
|
||||
================
|
||||
|
||||
meetings [0,30) [5,10) [15,20) -> rooms 2
|
||||
meetings [9,10) [10,11) [11,12) -> rooms 1
|
||||
|
||||
ropes [4, 3, 2, 6] heap: 29 sort once and fold: 29
|
||||
ropes [4, 4, 4, 4] heap: 32 sort once and fold: 36
|
||||
@@ -0,0 +1,16 @@
|
||||
Heap solutions vs brute force on seeded random input (seed 2026)
|
||||
================================================================
|
||||
|
||||
problem trials disagreements
|
||||
1 k-th largest 5000 0
|
||||
2 k-th largest in a stream 2000 0
|
||||
3 top k frequent (heap, buckets) 5000 0
|
||||
4 k closest points 5000 0
|
||||
5 last stone weight 5000 0
|
||||
6 merge k sorted lists 3000 0
|
||||
7 running median 1000 0
|
||||
8 task scheduler (vs search) 1500 0
|
||||
9 meeting rooms 5000 0
|
||||
10 connect ropes (vs all pairings) 1000 0
|
||||
|
||||
the sort-once-and-fold shortcut was wrong on 375 of those 1000 rope sets
|
||||
@@ -0,0 +1,50 @@
|
||||
java.util.PriorityQueue in JDK 25.0.5.1+2-LTS (lib/src.zip)
|
||||
===========================================================
|
||||
|
||||
291 private void grow(int minCapacity) {
|
||||
292 int oldCapacity = queue.length;
|
||||
293 // Double size if small; else grow by 50%
|
||||
294 int newCapacity = ArraysSupport.newLength(oldCapacity,
|
||||
295 minCapacity - oldCapacity, /* minimum growth */
|
||||
296 oldCapacity < 64 ? oldCapacity + 2 : oldCapacity >> 1
|
||||
297 /* preferred growth */);
|
||||
298 queue = Arrays.copyOf(queue, newCapacity);
|
||||
299 }
|
||||
|
||||
323 public boolean offer(E e) {
|
||||
324 if (e == null)
|
||||
325 throw new NullPointerException();
|
||||
326 modCount++;
|
||||
327 int i = size;
|
||||
328 if (i >= queue.length)
|
||||
329 grow(i + 1);
|
||||
330 siftUp(i, e);
|
||||
331 size = i + 1;
|
||||
332 return true;
|
||||
333 }
|
||||
|
||||
642 private static <T> void siftUpComparable(int k, T x, Object[] es) {
|
||||
643 Comparable<? super T> key = (Comparable<? super T>) x;
|
||||
644 while (k > 0) {
|
||||
645 int parent = (k - 1) >>> 1;
|
||||
646 Object e = es[parent];
|
||||
647 if (key.compareTo((T) e) >= 0)
|
||||
648 break;
|
||||
649 es[k] = e;
|
||||
650 k = parent;
|
||||
651 }
|
||||
652 es[k] = key;
|
||||
653 }
|
||||
|
||||
725 private void heapify() {
|
||||
726 final Object[] es = queue;
|
||||
727 int n = size, i = (n >>> 1) - 1;
|
||||
728 final Comparator<? super E> cmp;
|
||||
729 if ((cmp = comparator) == null)
|
||||
730 for (; i >= 0; i--)
|
||||
731 siftDownComparable(i, (E) es[i], es, n);
|
||||
732 else
|
||||
733 for (; i >= 0; i--)
|
||||
734 siftDownUsingComparator(i, (E) es[i], es, n, cmp);
|
||||
735 }
|
||||
|
||||
Reference in New Issue
Block a user