diff --git a/README.md b/README.md index c6046fd..88a8da6 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ One module per article. This repository currently holds: | [`quick-sort`](quick-sort/) | Quick Sort in Java: Lomuto vs Hoare Partition, Dry Run and Complexity | this commit | | [`bst`](bst/) | Binary Search Tree in Java: Insert, Delete, Search, Validate BST and LCA (With Dry Runs) | this commit | | [`merge-sort`](merge-sort/) | Merge Sort in Java: Recursive and Bottom-Up, Dry Run, Complexity and Counting Inversions | this commit | +| [`heap`](heap/) | Heap and PriorityQueue in Java: Top-K, Kth Largest, Merge K Sorted Lists and Running Median | this commit | ## `collections` module diff --git a/heap/README.md b/heap/README.md new file mode 100644 index 0000000..d73a68a --- /dev/null +++ b/heap/README.md @@ -0,0 +1,58 @@ +# heap + +Companion code for the ankurm.com article **Heap and PriorityQueue in Java: Top-K, Kth Largest, Merge K Sorted Lists and Running Median**. + +A binary heap built on a plain array (sift up, sift down, bottom-up heapify), `java.util.PriorityQueue` and its traps, +heap sort, and ten interview problems, each cross-checked against a brute-force answer on seeded random input. +Every figure and console line in the article is quoted from a file in `output/`, which the JUnit tests write while asserting +the same results. There is no `docs/` folder: the explanations live in the article itself. + +## Versions + +| Component | Version | +|---|---| +| JDK | Temurin 25.0.5.1+2 (LTS) | +| JUnit | 6.1.3 | +| Maven | 3.9.x | + +## Quickstart + +```bash +cd heap +export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH" +./scripts/run-all.sh # runs the tests and regenerates output/*.txt +``` + +The first Maven run must be online so the plugins land in the local cache. `23-jdk-source.txt` is read from +`$JAVA_HOME/lib/src.zip`, so a different JDK build can shift its line numbers. + +## Source layout + +``` +src/main/java/com/ankurm/interviewlab/heap/ +├── IntMinHeap.java array min-heap of ints (the teaching version) +├── BinaryHeap.java generic comparator heap with bottom-up heapify +├── HeapDryRun.java records every compare and swap +├── HeapSort.java in-place heap sort +├── PriorityQueueTour.java everyday PriorityQueue usage +├── Pitfalls.java iteration order, subtraction comparators, mutation, ties, exceptions +└── problems/ ten problems plus BruteForce.java +src/test/java/.../ tests that write output/ and assert it +``` + +## Captured output (`output/`) + +| File | What it shows | +|---|---| +| `01`, `02` | dry runs of offer (sift up) and poll (sift down), matching `PriorityQueue.toString()` | +| `03-same-array-as-jdk.txt` | my heaps and the JDK keep an identical backing array over 100,000 operations | +| `04-heapify-vs-offer.txt` | comparisons to build a heap of 1,000,000 keys, four ways | +| `05-operation-costs.txt` | `compareTo` / `equals` calls for peek, offer, poll, contains, remove | +| `06` to `10` | PriorityQueue tour, iteration order, subtraction comparator, mutation and ties, exceptions | +| `11` to `13` | heap sort trace, comparisons vs `Arrays.sort`, instability | +| `14` to `21` | the ten problems | +| `15-top-k-comparisons.txt` | sort vs size-k heap vs heapify-and-poll, nine input/k combinations | +| `22-brute-force-cross-checks.txt` | all ten problems against brute force | +| `23-jdk-source.txt` | `grow`, `offer`, `siftUpComparable`, `heapify` from the JDK's own source | + +Comparison counts are deterministic for these seeds; they are not timings. diff --git a/heap/output/01-dry-run-sift-up.txt b/heap/output/01-dry-run-sift-up.txt new file mode 100644 index 0000000..68d7780 --- /dev/null +++ b/heap/output/01-dry-run-sift-up.txt @@ -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] diff --git a/heap/output/02-dry-run-sift-down.txt b/heap/output/02-dry-run-sift-down.txt new file mode 100644 index 0000000..a35685b --- /dev/null +++ b/heap/output/02-dry-run-sift-down.txt @@ -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] diff --git a/heap/output/03-same-array-as-jdk.txt b/heap/output/03-same-array-as-jdk.txt new file mode 100644 index 0000000..be1c2e2 --- /dev/null +++ b/heap/output/03-same-array-as-jdk.txt @@ -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 diff --git a/heap/output/04-heapify-vs-offer.txt b/heap/output/04-heapify-vs-offer.txt new file mode 100644 index 0000000..09e256b --- /dev/null +++ b/heap/output/04-heapify-vs-offer.txt @@ -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 diff --git a/heap/output/05-operation-costs.txt b/heap/output/05-operation-costs.txt new file mode 100644 index 0000000..28710e0 --- /dev/null +++ b/heap/output/05-operation-costs.txt @@ -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 diff --git a/heap/output/06-priorityqueue-tour.txt b/heap/output/06-priorityqueue-tour.txt new file mode 100644 index 0000000..2dfb225 --- /dev/null +++ b/heap/output/06-priorityqueue-tour.txt @@ -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 diff --git a/heap/output/07-iteration-order.txt b/heap/output/07-iteration-order.txt new file mode 100644 index 0000000..fcfda75 --- /dev/null +++ b/heap/output/07-iteration-order.txt @@ -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) diff --git a/heap/output/08-subtraction-comparator.txt b/heap/output/08-subtraction-comparator.txt new file mode 100644 index 0000000..8e12aa3 --- /dev/null +++ b/heap/output/08-subtraction-comparator.txt @@ -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 diff --git a/heap/output/09-mutation-and-ties.txt b/heap/output/09-mutation-and-ties.txt new file mode 100644 index 0000000..4b84af9 --- /dev/null +++ b/heap/output/09-mutation-and-ties.txt @@ -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] diff --git a/heap/output/10-exceptions.txt b/heap/output/10-exceptions.txt new file mode 100644 index 0000000..a6cbf96 --- /dev/null +++ b/heap/output/10-exceptions.txt @@ -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 diff --git a/heap/output/11-heap-sort.txt b/heap/output/11-heap-sort.txt new file mode 100644 index 0000000..e0bc608 --- /dev/null +++ b/heap/output/11-heap-sort.txt @@ -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 diff --git a/heap/output/12-heap-sort-vs-arrays-sort.txt b/heap/output/12-heap-sort-vs-arrays-sort.txt new file mode 100644 index 0000000..d10959a --- /dev/null +++ b/heap/output/12-heap-sort-vs-arrays-sort.txt @@ -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 diff --git a/heap/output/13-heap-sort-not-stable.txt b/heap/output/13-heap-sort-not-stable.txt new file mode 100644 index 0000000..c024b2e --- /dev/null +++ b/heap/output/13-heap-sort-not-stable.txt @@ -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] diff --git a/heap/output/14-kth-largest.txt b/heap/output/14-kth-largest.txt new file mode 100644 index 0000000..f8eeb28 --- /dev/null +++ b/heap/output/14-kth-largest.txt @@ -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 diff --git a/heap/output/15-top-k-comparisons.txt b/heap/output/15-top-k-comparisons.txt new file mode 100644 index 0000000..458c4fe --- /dev/null +++ b/heap/output/15-top-k-comparisons.txt @@ -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 diff --git a/heap/output/16-top-k-frequent.txt b/heap/output/16-top-k-frequent.txt new file mode 100644 index 0000000..0471f48 --- /dev/null +++ b/heap/output/16-top-k-frequent.txt @@ -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] diff --git a/heap/output/17-closest-points-and-stones.txt b/heap/output/17-closest-points-and-stones.txt new file mode 100644 index 0000000..fb377a1 --- /dev/null +++ b/heap/output/17-closest-points-and-stones.txt @@ -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 diff --git a/heap/output/18-merge-k-sorted-lists.txt b/heap/output/18-merge-k-sorted-lists.txt new file mode 100644 index 0000000..d48d8c9 --- /dev/null +++ b/heap/output/18-merge-k-sorted-lists.txt @@ -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 diff --git a/heap/output/19-running-median.txt b/heap/output/19-running-median.txt new file mode 100644 index 0000000..16f03c7 --- /dev/null +++ b/heap/output/19-running-median.txt @@ -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 diff --git a/heap/output/20-task-scheduler.txt b/heap/output/20-task-scheduler.txt new file mode 100644 index 0000000..d38f293 --- /dev/null +++ b/heap/output/20-task-scheduler.txt @@ -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 diff --git a/heap/output/21-meeting-rooms-and-ropes.txt b/heap/output/21-meeting-rooms-and-ropes.txt new file mode 100644 index 0000000..e7b4c9b --- /dev/null +++ b/heap/output/21-meeting-rooms-and-ropes.txt @@ -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 diff --git a/heap/output/22-brute-force-cross-checks.txt b/heap/output/22-brute-force-cross-checks.txt new file mode 100644 index 0000000..2d5babc --- /dev/null +++ b/heap/output/22-brute-force-cross-checks.txt @@ -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 diff --git a/heap/output/23-jdk-source.txt b/heap/output/23-jdk-source.txt new file mode 100644 index 0000000..4e63fa6 --- /dev/null +++ b/heap/output/23-jdk-source.txt @@ -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 void siftUpComparable(int k, T x, Object[] es) { + 643 Comparable key = (Comparable) 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 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 } + diff --git a/heap/pom.xml b/heap/pom.xml new file mode 100644 index 0000000..6d0547d --- /dev/null +++ b/heap/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + com.ankurm.interviewlab + heap + 1.0.0 + jar + + java-interview-lab :: heap + + Runnable companion code for ankurm.com's "Heap and PriorityQueue in Java" article: array heaps, PriorityQueue and its traps, heap sort and ten interview problems with brute-force cross-checks. + + + + 25 + UTF-8 + 6.1.3 + + + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + + + + + org.junit.jupiter + junit-jupiter + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.6.0 + + -Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8 + + + + + diff --git a/heap/scripts/run-all.sh b/heap/scripts/run-all.sh new file mode 100755 index 0000000..38df9a6 --- /dev/null +++ b/heap/scripts/run-all.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online. +# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures +# in the article are assertions: they fail the build the moment they stop being true. +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p output +mvn -B -q -T1 test +echo "done:"; ls -1 output diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/BinaryHeap.java b/heap/src/main/java/com/ankurm/interviewlab/heap/BinaryHeap.java new file mode 100644 index 0000000..b5ec544 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/BinaryHeap.java @@ -0,0 +1,83 @@ +package com.ankurm.interviewlab.heap; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.NoSuchElementException; + +/** + * A generic array heap. The head is the smallest element according to the comparator, so + * a max-heap is simply {@code new BinaryHeap<>(Comparator.reverseOrder())}. + */ +public class BinaryHeap { + private final List a = new ArrayList<>(); + private final Comparator cmp; + + public BinaryHeap(Comparator cmp) { this.cmp = cmp; } + + /** Bottom-up build (Floyd): O(n), unlike n separate offers which are O(n log n) in the worst case. */ + public static BinaryHeap heapify(Collection items, Comparator cmp) { + BinaryHeap h = new BinaryHeap<>(cmp); + h.a.addAll(items); + for (int i = h.a.size() / 2 - 1; i >= 0; i--) h.siftDown(i); // from the last parent back to the root + return h; + } + + public void offer(E e) { + a.add(e); + siftUp(a.size() - 1); + } + + public E peek() { + if (a.isEmpty()) throw new NoSuchElementException("heap is empty"); + return a.get(0); + } + + public E poll() { + E head = peek(); + E last = a.remove(a.size() - 1); + if (!a.isEmpty()) { + a.set(0, last); + siftDown(0); + } + return head; + } + + public int size() { return a.size(); } + + public boolean isEmpty() { return a.isEmpty(); } + + public List asList() { return List.copyOf(a); } + + /** True when no child is smaller than its parent. */ + public boolean isValid() { + for (int i = 1; i < a.size(); i++) + if (cmp.compare(a.get((i - 1) / 2), a.get(i)) > 0) return false; + return true; + } + + private void siftUp(int i) { + E x = a.get(i); + while (i > 0) { + int parent = (i - 1) / 2; + if (cmp.compare(x, a.get(parent)) >= 0) break; + a.set(i, a.get(parent)); // move the parent down into the hole + i = parent; + } + a.set(i, x); + } + + private void siftDown(int i) { + int n = a.size(); + E x = a.get(i); + while (2 * i + 1 < n) { + int child = 2 * i + 1; + if (child + 1 < n && cmp.compare(a.get(child + 1), a.get(child)) < 0) child++; + if (cmp.compare(x, a.get(child)) <= 0) break; + a.set(i, a.get(child)); // move the smaller child up into the hole + i = child; + } + a.set(i, x); + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/HeapDryRun.java b/heap/src/main/java/com/ankurm/interviewlab/heap/HeapDryRun.java new file mode 100644 index 0000000..77e73f4 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/HeapDryRun.java @@ -0,0 +1,59 @@ +package com.ankurm.interviewlab.heap; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** The same steps as {@link IntMinHeap}, but every compare and swap is written down. */ +public class HeapDryRun { + private final int[] a = new int[32]; + private int size; + private final List log = new ArrayList<>(); + + public void offer(int v) { + a[size] = v; + log.add("offer(" + v + ") placed at index " + size + " " + state(size + 1)); + int i = size++; + while (i > 0) { + int p = (i - 1) / 2; + if (a[p] <= a[i]) { + log.add(" parent a[" + p + "]=" + a[p] + " <= " + a[i] + " stop"); + return; + } + log.add(" parent a[" + p + "]=" + a[p] + " > " + a[i] + " swap " + i + " <-> " + p); + swap(i, p); + i = p; + } + log.add(" reached the root " + state(size)); + } + + public int poll() { + int min = a[0]; + a[0] = a[--size]; + log.add("poll() returns " + min + "; last value moved to root " + state(size)); + int i = 0; + while (2 * i + 1 < size) { + int c = 2 * i + 1; + if (c + 1 < size && a[c + 1] < a[c]) c++; + if (a[i] <= a[c]) { + log.add(" smaller child a[" + c + "]=" + a[c] + " >= " + a[i] + " stop " + state(size)); + return min; + } + log.add(" smaller child a[" + c + "]=" + a[c] + " < " + a[i] + " swap " + i + " <-> " + c); + swap(i, c); + i = c; + } + log.add(" reached a leaf " + state(size)); + return min; + } + + public List log() { return log; } + + public String state(int n) { return Arrays.toString(Arrays.copyOf(a, n)); } + + private void swap(int i, int j) { + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/HeapSort.java b/heap/src/main/java/com/ankurm/interviewlab/heap/HeapSort.java new file mode 100644 index 0000000..15af0ea --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/HeapSort.java @@ -0,0 +1,55 @@ +package com.ankurm.interviewlab.heap; + +import java.util.Comparator; + +/** In-place heap sort: build a max-heap, then repeatedly swap the maximum to the end. */ +public final class HeapSort { + private HeapSort() {} + + public static void sort(int[] a) { + int n = a.length; + for (int i = n / 2 - 1; i >= 0; i--) siftDown(a, i, n); // phase 1: heapify, O(n) + for (int end = n - 1; end > 0; end--) { // phase 2: n-1 removals, O(n log n) + int t = a[0]; + a[0] = a[end]; + a[end] = t; + siftDown(a, 0, end); // the heap is now a[0..end-1] + } + } + + private static void siftDown(int[] a, int i, int n) { + int x = a[i]; + while (2 * i + 1 < n) { + int child = 2 * i + 1; + if (child + 1 < n && a[child + 1] > a[child]) child++; // the LARGER child: max-heap + if (x >= a[child]) break; + a[i] = a[child]; + i = child; + } + a[i] = x; + } + + /** The same algorithm for objects, used to count comparisons and to show that it is not stable. */ + public static void sort(T[] a, Comparator cmp) { + int n = a.length; + for (int i = n / 2 - 1; i >= 0; i--) siftDown(a, i, n, cmp); + for (int end = n - 1; end > 0; end--) { + T t = a[0]; + a[0] = a[end]; + a[end] = t; + siftDown(a, 0, end, cmp); + } + } + + private static void siftDown(T[] a, int i, int n, Comparator cmp) { + T x = a[i]; + while (2 * i + 1 < n) { + int child = 2 * i + 1; + if (child + 1 < n && cmp.compare(a[child + 1], a[child]) > 0) child++; + if (cmp.compare(x, a[child]) >= 0) break; + a[i] = a[child]; + i = child; + } + a[i] = x; + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/IntMinHeap.java b/heap/src/main/java/com/ankurm/interviewlab/heap/IntMinHeap.java new file mode 100644 index 0000000..cebf24d --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/IntMinHeap.java @@ -0,0 +1,63 @@ +package com.ankurm.interviewlab.heap; + +import java.util.Arrays; +import java.util.NoSuchElementException; + +/** A binary min-heap of ints stored in a plain array. The smallest value is always at index 0. */ +public class IntMinHeap { + private int[] a = new int[8]; + private int size; + + public void offer(int value) { + if (size == a.length) a = Arrays.copyOf(a, size * 2); + a[size] = value; // 1. put it in the next free slot (keeps the tree complete) + siftUp(size++); // 2. let it climb until its parent is not larger + } + + public int peek() { + if (size == 0) throw new NoSuchElementException("heap is empty"); + return a[0]; + } + + public int poll() { + int min = peek(); + a[0] = a[--size]; // 1. move the last value into the root + siftDown(0); // 2. let it sink below any smaller child + return min; + } + + public int size() { return size; } + + public boolean isEmpty() { return size == 0; } + + /** The used part of the backing array, in storage order (level by level). */ + public int[] toArray() { return Arrays.copyOf(a, size); } + + private void siftUp(int i) { + while (i > 0) { + int parent = (i - 1) / 2; + if (a[parent] <= a[i]) return; + swap(i, parent); + i = parent; + } + } + + private void siftDown(int i) { + while (true) { + int left = 2 * i + 1; + if (left >= size) return; // a leaf: nowhere to go + int child = left; + int right = left + 1; + if (right < size && a[right] < a[left]) child = right; // the SMALLER child + if (a[i] <= a[child]) return; + swap(i, child); + i = child; + } + } + + private void swap(int i, int j) { + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/Pitfalls.java b/heap/src/main/java/com/ankurm/interviewlab/heap/Pitfalls.java new file mode 100644 index 0000000..7e9238b --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/Pitfalls.java @@ -0,0 +1,134 @@ +package com.ankurm.interviewlab.heap; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; + +/** Seven ways to get a surprising answer from java.util.PriorityQueue. Every line is real output. */ +public final class Pitfalls { + private Pitfalls() {} + + /** A mutable element: changing its key while it sits in the queue does NOT move it. */ + public static final class Job { + final String name; + public int cost; + + public Job(String name, int cost) { + this.name = name; + this.cost = cost; + } + + @Override public String toString() { return name + ":" + cost; } + } + + record Ticket(int priority, String name) {} + + record SequencedTicket(int priority, long seq, String name) {} + + public static List iterationOrder() { + List out = new ArrayList<>(); + PriorityQueue q = new PriorityQueue<>(List.of(35, 20, 50, 10, 40, 5)); + PriorityQueue offered = new PriorityQueue<>(); + for (int v : new int[] {35, 20, 50, 10, 40, 5}) offered.add(v); + out.add("built by add() x 6 : " + offered); + out.add("toString() : " + q); + List forEach = new ArrayList<>(); + for (int v : q) forEach.add(v); + out.add("for-each : " + forEach); + out.add("stream().toList() : " + q.stream().toList()); + Object[] copy = q.toArray(); + Arrays.sort(copy); + out.add("sorted toArray() : " + Arrays.toString(copy)); + out.add("stream().sorted() : " + q.stream().sorted().toList()); + List polled = new ArrayList<>(); + while (!q.isEmpty()) polled.add(q.poll()); + out.add("repeated poll() : " + polled + " (size is now " + q.size() + ")"); + return out; + } + + public static List subtractionComparator() { + List out = new ArrayList<>(); + int[] values = {1, Integer.MIN_VALUE, 100}; + PriorityQueue bad = new PriorityQueue<>((x, y) -> x - y); + PriorityQueue good = new PriorityQueue<>(Integer::compare); + for (int v : values) { + bad.add(v); + good.add(v); + } + out.add("input : " + Arrays.toString(values)); + out.add("(x, y) -> x - y head : " + bad.peek()); + out.add("Integer::compare head : " + good.peek()); + out.add("1 - Integer.MIN_VALUE = " + (1 - Integer.MIN_VALUE) + " (negative, so 1 'sorts before' MIN_VALUE)"); + PriorityQueue badMax = new PriorityQueue<>((x, y) -> y - x); + badMax.add(Integer.MIN_VALUE); + badMax.add(7); + out.add("(x, y) -> y - x max-heap of [MIN_VALUE, 7], head: " + badMax.peek()); + return out; + } + + public static List mutationAfterInsert() { + List out = new ArrayList<>(); + PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt((Job j) -> j.cost)); + Job a = new Job("A", 10), b = new Job("B", 20), c = new Job("C", 30); + q.add(a); + q.add(b); + q.add(c); + c.cost = 1; // the queue is not told + out.add("after c.cost = 1, peek() : " + q.peek()); + out.add("polled in order : " + q.poll() + ", " + q.poll() + ", " + q.poll()); + + PriorityQueue r = new PriorityQueue<>(Comparator.comparingInt((Job j) -> j.cost)); + Job x = new Job("A", 10), y = new Job("B", 20), z = new Job("C", 30); + r.add(x); + r.add(y); + r.add(z); + r.remove(z); // take it out ... + z.cost = 1; // ... change it ... + r.add(z); // ... put it back + out.add("remove, change, add, polled : " + r.poll() + ", " + r.poll() + ", " + r.poll()); + return out; + } + + public static List tiesAreNotFifo() { + List out = new ArrayList<>(); + PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(Ticket::priority)); + for (String n : new String[] {"first", "second", "third", "fourth", "fifth"}) q.add(new Ticket(1, n)); + List order = new ArrayList<>(); + while (!q.isEmpty()) order.add(q.poll().name()); + out.add("equal priority, comparator on priority only : " + order); + + PriorityQueue s = new PriorityQueue<>( + Comparator.comparingInt(SequencedTicket::priority).thenComparingLong(SequencedTicket::seq)); + long seq = 0; + for (String n : new String[] {"first", "second", "third", "fourth", "fifth"}) s.add(new SequencedTicket(1, seq++, n)); + List fifo = new ArrayList<>(); + while (!s.isEmpty()) fifo.add(s.poll().name()); + out.add("with a sequence number as the tie-breaker : " + fifo); + return out; + } + + public static List exceptions() { + List out = new ArrayList<>(); + out.add(attempt("add(null)", () -> new PriorityQueue().add(null))); + out.add(attempt("add(new Object()) to an empty queue", () -> new PriorityQueue<>().add(new Object()))); + out.add(attempt("new PriorityQueue<>(0)", () -> new PriorityQueue<>(0))); + out.add(attempt("add while iterating", () -> { + PriorityQueue q = new PriorityQueue<>(List.of(1, 2, 3)); + for (Integer v : q) q.add(v + 10); + })); + return out; + } + + private static String attempt(String label, Runnable r) { + try { + r.run(); + return label + " : no exception"; + } catch (RuntimeException e) { + String m = e.getMessage(); + if (m != null && m.length() > 90) m = m.substring(0, 90) + "..."; + return label + " : " + e.getClass().getSimpleName() + (m == null ? "" : " - " + m); + } + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/PriorityQueueTour.java b/heap/src/main/java/com/ankurm/interviewlab/heap/PriorityQueueTour.java new file mode 100644 index 0000000..e088bdf --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/PriorityQueueTour.java @@ -0,0 +1,62 @@ +package com.ankurm.interviewlab.heap; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; + +/** Everyday PriorityQueue usage. Run it: the returned lines are committed in output/04-*.txt. */ +public final class PriorityQueueTour { + private PriorityQueueTour() {} + + public record Task(String name, int priority, int minutes) {} + + public static List run() { + List out = new ArrayList<>(); + + Queue min = new PriorityQueue<>(); // smallest first + Queue max = new PriorityQueue<>(Collections.reverseOrder()); // largest first + for (int v : new int[] {35, 20, 50, 10, 40, 5}) { + min.offer(v); + max.offer(v); + } + out.add("min.peek() = " + min.peek()); + out.add("max.peek() = " + max.peek()); + out.add("min drained = " + drain(min)); + out.add("max drained = " + drain(max)); + + // Objects: build the ordering with Comparator.comparing, never with subtraction + Comparator byUrgency = Comparator + .comparingInt(Task::priority).reversed() // higher priority first + .thenComparingInt(Task::minutes) // then the shorter job + .thenComparing(Task::name); // then alphabetical: no ambiguity left + Queue tasks = new PriorityQueue<>(byUrgency); + tasks.add(new Task("write-report", 2, 60)); + tasks.add(new Task("fix-prod-bug", 5, 90)); + tasks.add(new Task("reply-email", 2, 5)); + tasks.add(new Task("deploy", 5, 15)); + tasks.add(new Task("code-review", 3, 30)); + while (!tasks.isEmpty()) { + Task t = tasks.poll(); + out.add("poll -> " + t.name() + " (priority " + t.priority() + ", " + t.minutes() + " min)"); + } + + Queue empty = new PriorityQueue<>(); + out.add("empty.peek() = " + empty.peek()); + out.add("empty.poll() = " + empty.poll()); + try { + empty.element(); + } catch (RuntimeException e) { + out.add("empty.element() throws " + e.getClass().getSimpleName()); + } + return out; + } + + static List drain(Queue q) { + List r = new ArrayList<>(); + while (!q.isEmpty()) r.add(q.poll()); + return r; + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/BruteForce.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/BruteForce.java new file mode 100644 index 0000000..e6d90bd --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/BruteForce.java @@ -0,0 +1,112 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Deliberately simple (and slow) answers, used only to cross-check the heap solutions on random input. */ +public final class BruteForce { + private BruteForce() {} + + public static int kthLargest(int[] nums, int k) { + int[] s = nums.clone(); + Arrays.sort(s); + return s[s.length - k]; + } + + public static List topKFrequent(int[] nums, int k) { + Map count = new LinkedHashMap<>(); + for (int x : nums) count.merge(x, 1, Integer::sum); + List values = new ArrayList<>(count.keySet()); + values.sort((a, b) -> count.get(a).equals(count.get(b)) ? Integer.compare(a, b) + : Integer.compare(count.get(b), count.get(a))); + return values.subList(0, Math.min(k, values.size())); + } + + /** The multiset of the k smallest squared distances. */ + public static long[] kClosestDistances(int[][] points, int k) { + return Arrays.stream(points).mapToLong(KClosestPoints::distance).sorted().limit(k).toArray(); + } + + public static int lastStone(int[] stones) { + int[] s = stones.clone(); + int n = s.length; + while (n > 1) { + Arrays.sort(s, 0, n); + int diff = s[n - 1] - s[n - 2]; + n -= 2; + if (diff > 0) s[n++] = diff; + } + return n == 0 ? 0 : s[0]; + } + + public static int[] flattenAndSort(int[][] lists) { + return Arrays.stream(lists).flatMapToInt(Arrays::stream).sorted().toArray(); + } + + public static double median(int[] values, int n) { + int[] s = Arrays.copyOf(values, n); + Arrays.sort(s); + return n % 2 == 1 ? s[n / 2] : ((long) s[n / 2 - 1] + s[n / 2]) / 2.0; + } + + /** Tries every choice (any ready task, or idle) at every time step. Exponential: small inputs only. */ + public static int shortestSchedule(String tasks, int n) { + int[] left = new int[26]; + for (char c : tasks.toCharArray()) left[c - 'A']++; + return search(left, new int[26], n, new HashMap<>()); + } + + private static int search(int[] left, int[] wait, int n, Map memo) { + if (Arrays.stream(left).sum() == 0) return 0; + String key = Arrays.toString(left) + Arrays.toString(wait); + Integer known = memo.get(key); + if (known != null) return known; + int[] cooled = wait.clone(); + boolean waiting = false; + for (int i = 0; i < 26; i++) { + if (left[i] > 0 && wait[i] > 0) waiting = true; + if (cooled[i] > 0) cooled[i]--; + } + int best = waiting ? 1 + search(left, cooled, n, memo) : Integer.MAX_VALUE; // idle one unit + for (int i = 0; i < 26; i++) { + if (left[i] == 0 || wait[i] > 0) continue; + int[] l = left.clone(), w = cooled.clone(); + l[i]--; + w[i] = n; + best = Math.min(best, 1 + search(l, w, n, memo)); + } + memo.put(key, best); + return best; + } + + /** The largest number of meetings running at any meeting's start time. */ + public static int minRooms(int[][] meetings) { + int best = 0; + for (int[] m : meetings) { + int running = 0; + for (int[] o : meetings) if (o[0] <= m[0] && m[0] < o[1]) running++; + best = Math.max(best, running); + } + return best; + } + + /** Tries every pair at every step. Factorial: small inputs only. */ + public static long minRopeCost(long[] ropes) { + if (ropes.length < 2) return 0; + long best = Long.MAX_VALUE; + for (int i = 0; i < ropes.length; i++) { + for (int j = i + 1; j < ropes.length; j++) { + long[] next = new long[ropes.length - 1]; + int k = 0; + for (int t = 0; t < ropes.length; t++) if (t != i && t != j) next[k++] = ropes[t]; + next[k] = ropes[i] + ropes[j]; + best = Math.min(best, next[k] + minRopeCost(next)); + } + } + return best; + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/ConnectRopes.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/ConnectRopes.java new file mode 100644 index 0000000..f58151f --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/ConnectRopes.java @@ -0,0 +1,33 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.Arrays; +import java.util.PriorityQueue; + +/** Problem 10: join ropes two at a time, paying the combined length each time; minimise the total cost. */ +public final class ConnectRopes { + private ConnectRopes() {} + + public static long minCost(int[] ropes) { + PriorityQueue heap = new PriorityQueue<>(); + for (int r : ropes) heap.offer((long) r); + long cost = 0; + while (heap.size() > 1) { + long joined = heap.poll() + heap.poll(); // always the two shortest, INCLUDING joined ropes + cost += joined; + heap.offer(joined); + } + return cost; + } + + /** Looks right, is wrong: sorting once forgets that a joined rope has to compete with the others. */ + public static long sortOnceAndFold(int[] ropes) { + int[] s = ropes.clone(); + Arrays.sort(s); + long length = s.length == 0 ? 0 : s[0], cost = 0; + for (int i = 1; i < s.length; i++) { + length += s[i]; + cost += length; + } + return cost; + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KClosestPoints.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KClosestPoints.java new file mode 100644 index 0000000..c23f1c7 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KClosestPoints.java @@ -0,0 +1,26 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; + +/** Problem 4: the k points closest to the origin. A MAX-heap of size k whose head is the farthest kept point. */ +public final class KClosestPoints { + private KClosestPoints() {} + + /** Squared distance in long arithmetic: no square roots and no int overflow. */ + public static long distance(int[] p) { + return (long) p[0] * p[0] + (long) p[1] * p[1]; + } + + public static List find(int[][] points, int k) { + Comparator farthestFirst = Comparator.comparingLong(KClosestPoints::distance).reversed(); + PriorityQueue heap = new PriorityQueue<>(farthestFirst); + for (int[] p : points) { + heap.offer(p); + if (heap.size() > k) heap.poll(); // throw away the farthest + } + return new ArrayList<>(heap); // "any order" is allowed by the problem + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KthLargest.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KthLargest.java new file mode 100644 index 0000000..70edb34 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KthLargest.java @@ -0,0 +1,22 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.PriorityQueue; + +/** Problem 1: the k-th largest element. Keep a MIN-heap of the k largest seen so far. O(n log k) time, O(k) space. */ +public final class KthLargest { + private KthLargest() {} + + public static int find(int[] nums, int k) { + if (k < 1 || k > nums.length) throw new IllegalArgumentException("k out of range: " + k); + PriorityQueue top = new PriorityQueue<>(k); + for (int x : nums) { + if (top.size() < k) { + top.offer(x); + } else if (x > top.peek()) { // beats the weakest of the current top k + top.poll(); + top.offer(x); + } + } + return top.peek(); // the weakest of the top k IS the k-th largest + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KthLargestStream.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KthLargestStream.java new file mode 100644 index 0000000..6cc8df6 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/KthLargestStream.java @@ -0,0 +1,22 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.PriorityQueue; + +/** Problem 2: the k-th largest of a stream. Same heap, kept between calls. add() is O(log k). */ +public final class KthLargestStream { + private final int k; + private final PriorityQueue top = new PriorityQueue<>(); + + public KthLargestStream(int k, int[] initial) { + if (k < 1) throw new IllegalArgumentException("k must be positive"); + this.k = k; + for (int x : initial) add(x); + } + + /** Adds a value; returns the k-th largest so far, or null while fewer than k values have arrived. */ + public Integer add(int value) { + top.offer(value); + if (top.size() > k) top.poll(); + return top.size() == k ? top.peek() : null; + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/LastStoneWeight.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/LastStoneWeight.java new file mode 100644 index 0000000..4ccb3a6 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/LastStoneWeight.java @@ -0,0 +1,20 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.Collections; +import java.util.PriorityQueue; + +/** Problem 5: smash the two heaviest stones until at most one remains. A max-heap, O(n log n). */ +public final class LastStoneWeight { + private LastStoneWeight() {} + + public static int solve(int[] stones) { + PriorityQueue heap = new PriorityQueue<>(Collections.reverseOrder()); + for (int s : stones) heap.offer(s); + while (heap.size() > 1) { + int y = heap.poll(); + int x = heap.poll(); + if (y > x) heap.offer(y - x); + } + return heap.isEmpty() ? 0 : heap.peek(); + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/MeetingRooms.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/MeetingRooms.java new file mode 100644 index 0000000..44a2fca --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/MeetingRooms.java @@ -0,0 +1,21 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.PriorityQueue; + +/** Problem 9: the minimum number of rooms for meetings [start, end). Min-heap of end times, O(n log n). */ +public final class MeetingRooms { + private MeetingRooms() {} + + public static int minRooms(int[][] meetings) { + int[][] byStart = meetings.clone(); + Arrays.sort(byStart, Comparator.comparingInt(m -> m[0])); + PriorityQueue endTimes = new PriorityQueue<>(); + for (int[] m : byStart) { + if (!endTimes.isEmpty() && endTimes.peek() <= m[0]) endTimes.poll(); // reuse that room + endTimes.offer(m[1]); + } + return endTimes.size(); + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/MergeKSortedLists.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/MergeKSortedLists.java new file mode 100644 index 0000000..0088aa2 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/MergeKSortedLists.java @@ -0,0 +1,66 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.Comparator; +import java.util.PriorityQueue; + +/** Problem 6: merge k sorted linked lists. The heap holds one node per list. O(N log k) for N nodes in total. */ +public final class MergeKSortedLists { + private MergeKSortedLists() {} + + public static final class Node { + public final int val; + public Node next; + + public Node(int val) { this.val = val; } + } + + public static Node merge(Node[] lists) { + return merge(lists, Comparator.comparingInt(n -> n.val)); + } + + public static Node merge(Node[] lists, Comparator order) { + PriorityQueue heads = new PriorityQueue<>(order); + for (Node n : lists) if (n != null) heads.offer(n); // PriorityQueue rejects null + Node dummy = new Node(0), tail = dummy; + while (!heads.isEmpty()) { + Node smallest = heads.poll(); + tail.next = smallest; + tail = smallest; + if (smallest.next != null) heads.offer(smallest.next); + } + return dummy.next; + } + + /** Merge list 1 into the result, then list 2, and so on: correct, but O(N k). */ + public static Node mergeOneByOne(Node[] lists, Comparator order) { + Node result = null; + for (Node n : lists) result = mergeTwo(result, n, order); + return result; + } + + /** Pair the lists up like merge sort: O(N log k), no heap. */ + public static Node mergeInPairs(Node[] lists, Comparator order) { + if (lists.length == 0) return null; + Node[] work = lists.clone(); + for (int step = 1; step < work.length; step *= 2) + for (int i = 0; i + step < work.length; i += 2 * step) + work[i] = mergeTwo(work[i], work[i + step], order); + return work[0]; + } + + static Node mergeTwo(Node a, Node b, Comparator order) { + Node dummy = new Node(0), tail = dummy; + while (a != null && b != null) { + if (order.compare(a, b) <= 0) { + tail.next = a; + a = a.next; + } else { + tail.next = b; + b = b.next; + } + tail = tail.next; + } + tail.next = a != null ? a : b; + return dummy.next; + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/RunningMedian.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/RunningMedian.java new file mode 100644 index 0000000..4d7a3b3 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/RunningMedian.java @@ -0,0 +1,32 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.Collections; +import java.util.PriorityQueue; + +/** + * Problem 7: the median of a stream. Two heaps meet in the middle: + * lower (max-heap) holds the smaller half, upper (min-heap) holds the larger half, + * and lower has either the same number of elements as upper or exactly one more. + */ +public final class RunningMedian { + private final PriorityQueue lower = new PriorityQueue<>(Collections.reverseOrder()); + private final PriorityQueue upper = new PriorityQueue<>(); + + public void add(int x) { // O(log n) + if (lower.isEmpty() || x <= lower.peek()) lower.offer(x); + else upper.offer(x); + if (lower.size() > upper.size() + 1) upper.offer(lower.poll()); + else if (upper.size() > lower.size()) lower.offer(upper.poll()); + } + + public double median() { // O(1) + if (lower.isEmpty()) throw new IllegalStateException("no values yet"); + if (lower.size() > upper.size()) return lower.peek(); + return ((long) lower.peek() + upper.peek()) / 2.0; // widen BEFORE adding + } + + public String halves() { + return "lower(max-heap)=" + lower.stream().sorted().toList() + + " upper(min-heap)=" + upper.stream().sorted().toList(); + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/TaskScheduler.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/TaskScheduler.java new file mode 100644 index 0000000..b810030 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/TaskScheduler.java @@ -0,0 +1,66 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.ArrayDeque; +import java.util.Comparator; +import java.util.PriorityQueue; + +/** + * Problem 8: task scheduler. Each task takes one time unit; two runs of the same letter need at least + * n units between them. Always run the available task with the most copies left. + */ +public final class TaskScheduler { + private TaskScheduler() {} + + private static final class Pending { + final char name; + int left; + int readyAt; + + Pending(char name, int left) { + this.name = name; + this.left = left; + } + } + + /** Returns the timeline, one character per time unit, '.' for idle. Its length is the answer. */ + public static String schedule(String tasks, int n) { + int[] count = new int[26]; + for (char c : tasks.toCharArray()) count[c - 'A']++; + PriorityQueue ready = new PriorityQueue<>( + Comparator.comparingInt(p -> p.left).reversed().thenComparingInt(p -> p.name)); + for (int i = 0; i < 26; i++) if (count[i] > 0) ready.offer(new Pending((char) ('A' + i), count[i])); + ArrayDeque cooling = new ArrayDeque<>(); // FIFO is enough: readyAt only increases + StringBuilder timeline = new StringBuilder(); + for (int time = 0; !ready.isEmpty() || !cooling.isEmpty(); time++) { + if (!cooling.isEmpty() && cooling.peek().readyAt <= time) ready.offer(cooling.poll()); + Pending p = ready.poll(); + if (p == null) { + timeline.append('.'); + continue; + } + timeline.append(p.name); + if (--p.left > 0) { + p.readyAt = time + n + 1; // safe to mutate: p is OUTSIDE the heap now + cooling.add(p); + } + } + return timeline.toString(); + } + + /** The O(N) counting formula for the length only. */ + public static int formula(String tasks, int n) { + int[] count = new int[26]; + for (char c : tasks.toCharArray()) count[c - 'A']++; + int max = 0, atMax = 0; + for (int c : count) { + if (c > max) { + max = c; + atMax = 1; + } else if (c == max) { + atMax++; + } + } + if (max == 0) return 0; + return Math.max(tasks.length(), (max - 1) * (n + 1) + atMax); + } +} diff --git a/heap/src/main/java/com/ankurm/interviewlab/heap/problems/TopKFrequent.java b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/TopKFrequent.java new file mode 100644 index 0000000..d4bcd04 --- /dev/null +++ b/heap/src/main/java/com/ankurm/interviewlab/heap/problems/TopKFrequent.java @@ -0,0 +1,78 @@ +package com.ankurm.interviewlab.heap.problems; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; + +/** Problem 3: the k most frequent values. Order of the answer: higher count first, ties by smaller value. */ +public final class TopKFrequent { + private TopKFrequent() {} + + /** Count, then a size-k heap whose head is the WORST of the kept entries. O(n + d log k), d = distinct values. */ + public static List byHeap(int[] nums, int k) { + Map count = count(nums); + // worst first: fewer occurrences, and among equals the LARGER value (it loses the tie) + Comparator> worstFirst = Comparator + .>comparingInt(Map.Entry::getValue) + .thenComparing(Map.Entry::getKey, Comparator.reverseOrder()); + PriorityQueue> heap = new PriorityQueue<>(worstFirst); + for (Map.Entry e : count.entrySet()) { + heap.offer(e); + if (heap.size() > k) heap.poll(); + } + LinkedList answer = new LinkedList<>(); + while (!heap.isEmpty()) answer.addFirst(heap.poll().getKey()); // worst comes out first + return answer; + } + + /** Bucket sort on the count: a value can occur at most n times, so index buckets by count. O(n) plus tie sorting. */ + public static List byBuckets(int[] nums, int k) { + Map count = count(nums); + List> bucket = new ArrayList<>(); + for (int i = 0; i <= nums.length; i++) bucket.add(new ArrayList<>()); + count.forEach((value, c) -> bucket.get(c).add(value)); + List answer = new ArrayList<>(); + for (int c = nums.length; c > 0 && answer.size() < k; c--) { + bucket.get(c).sort(null); + for (int v : bucket.get(c)) { + if (answer.size() == k) break; + answer.add(v); + } + } + return answer; + } + + /** The word variant: higher count first, ties alphabetically. */ + public static List words(String[] words, int k) { + return topWords(words, k, Comparator.reverseOrder()); + } + + /** The common bug: the tie-breaker is not reversed inside the worst-first heap. */ + public static List wordsWithWrongTieBreak(String[] words, int k) { + return topWords(words, k, Comparator.naturalOrder()); + } + + private static List topWords(String[] words, int k, Comparator tieInHeap) { + Map count = new HashMap<>(); + for (String w : words) count.merge(w, 1, Integer::sum); + PriorityQueue heap = new PriorityQueue<>( + Comparator.comparingInt(count::get).thenComparing(tieInHeap)); + for (String w : count.keySet()) { + heap.offer(w); + if (heap.size() > k) heap.poll(); + } + LinkedList answer = new LinkedList<>(); + while (!heap.isEmpty()) answer.addFirst(heap.poll()); + return answer; + } + + private static Map count(int[] nums) { + Map count = new HashMap<>(); + for (int x : nums) count.merge(x, 1, Integer::sum); + return count; + } +} diff --git a/heap/src/test/java/com/ankurm/interviewlab/heap/HeapBasicsTest.java b/heap/src/test/java/com/ankurm/interviewlab/heap/HeapBasicsTest.java new file mode 100644 index 0000000..534cfde --- /dev/null +++ b/heap/src/test/java/com/ankurm/interviewlab/heap/HeapBasicsTest.java @@ -0,0 +1,287 @@ +package com.ankurm.interviewlab.heap; + +import com.ankurm.interviewlab.heap.support.Data; +import com.ankurm.interviewlab.heap.support.Data.Counter; +import com.ankurm.interviewlab.heap.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.*; + +class HeapBasicsTest { + + @Test + void dryRun() { + int[] input = {35, 20, 50, 10, 40, 5}; + HeapDryRun d = new HeapDryRun(); + IntMinHeap h = new IntMinHeap(); + PriorityQueue pq = new PriorityQueue<>(); + for (int v : input) { + d.offer(v); + h.offer(v); + pq.offer(v); + } + assertEquals("[5, 20, 10, 35, 40, 50]", Arrays.toString(h.toArray())); + assertEquals(Arrays.toString(h.toArray()), pq.toString()); + Transcript t = Transcript.start("01-dry-run-sift-up.txt", "Min-heap: offer " + Arrays.toString(input) + " one at a time"); + d.log().forEach(t::line); + t.blank().line("final array : " + Arrays.toString(h.toArray())); + t.line("java.util.PriorityQueue shows: " + pq); + t.flush(); + + int before = d.log().size(); + assertEquals(5, d.poll()); + assertEquals(10, d.poll()); + h.poll(); + h.poll(); + pq.poll(); + pq.poll(); + assertEquals(Arrays.toString(h.toArray()), pq.toString()); + Transcript u = Transcript.start("02-dry-run-sift-down.txt", "Min-heap: two poll() calls on [5, 20, 10, 35, 40, 50]"); + d.log().subList(before, d.log().size()).forEach(u::line); + u.blank().line("final array : " + Arrays.toString(h.toArray())); + u.line("java.util.PriorityQueue shows: " + pq); + u.flush(); + } + + @Test + void sameArrayAsTheJdk() { + Random r = new Random(7); + long operations = 0, heapifyRuns = 0; + for (int round = 0; round < 500; round++) { + IntMinHeap mine = new IntMinHeap(); + BinaryHeap generic = new BinaryHeap<>(Comparator.naturalOrder()); + PriorityQueue jdk = new PriorityQueue<>(); + for (int op = 0; op < 200; op++) { + if (jdk.isEmpty() || r.nextInt(3) > 0) { + int v = r.nextInt(50); + mine.offer(v); + generic.offer(v); + jdk.offer(v); + } else { + int expected = jdk.poll(); + assertEquals(expected, mine.poll()); + assertEquals(expected, generic.poll()); + } + assertArrayEquals(jdk.stream().mapToInt(Integer::intValue).toArray(), mine.toArray()); + assertEquals(new ArrayList<>(jdk), generic.asList()); + assertTrue(generic.isValid()); + operations++; + } + List items = Arrays.stream(Data.ints(r, r.nextInt(100), 20)).boxed().toList(); + assertEquals(new ArrayList<>(new PriorityQueue<>(items)), + BinaryHeap.heapify(items, Comparator.naturalOrder()).asList()); + heapifyRuns++; + } + Transcript.start("03-same-array-as-jdk.txt", "My heaps vs java.util.PriorityQueue (seed 7)") + .line("random offer/poll operations compared : " + operations) + .line(" backing array identical after every one: IntMinHeap, BinaryHeap and PriorityQueue") + .line("bottom-up builds compared : " + heapifyRuns) + .line(" BinaryHeap.heapify(list) and new PriorityQueue<>(list) produced the same array every time") + .flush(); + } + + /** Comparable wrapper that counts compareTo calls, because new PriorityQueue<>(collection) takes no comparator. */ + static long calls; + + record Key(int v) implements Comparable { + @Override public int compareTo(Key o) { + calls++; + return Integer.compare(v, o.v); + } + } + + @Test + void heapifyVersusRepeatedOffer() { + int n = 1_000_000; + Transcript t = Transcript.start("04-heapify-vs-offer.txt", "Building a min-heap of n = 1,000,000 keys: comparisons"); + t.line(String.format("%-12s %18s %18s %22s %22s", "input", "my offer() x n", "my heapify", "PriorityQueue.addAll", "new PriorityQueue(list)")); + for (String shape : new String[] {"random", "ascending", "descending"}) { + List items = Data.sequence(shape, n); + Counter a = new Counter<>(Comparator.naturalOrder()); + BinaryHeap h = new BinaryHeap<>(a); + items.forEach(h::offer); + long offers = a.count; + Counter b = new Counter<>(Comparator.naturalOrder()); + BinaryHeap built = BinaryHeap.heapify(items, b); + long heapify = b.count; + assertTrue(h.isValid()); + assertTrue(built.isValid()); + + List keys = items.stream().map(Key::new).toList(); + calls = 0; + PriorityQueue q1 = new PriorityQueue<>(); + q1.addAll(keys); + long addAll = calls; + calls = 0; + PriorityQueue q2 = new PriorityQueue<>(keys); + long ctor = calls; + assertEquals(q1.peek(), q2.peek()); + assertEquals(offers, addAll); + assertEquals(heapify, ctor); + assertTrue(ctor < 2L * n); + if (shape.equals("descending")) assertTrue(addAll > 8 * ctor); + t.line(String.format("%-12s %,18d %,18d %,22d %,22d", shape, offers, heapify, addAll, ctor)); + } + t.flush(); + } + + static long equalsCalls; + + record Id(int v) implements Comparable { + @Override public boolean equals(Object o) { + equalsCalls++; + return o instanceof Id i && i.v == v; + } + @Override public int hashCode() { return v; } + @Override public int compareTo(Id o) { + calls++; + return Integer.compare(v, o.v); + } + } + + @Test + void cheapAndExpensiveOperations() { + int n = 1_000_000; + PriorityQueue q = new PriorityQueue<>(Data.sequence("random", n).stream().map(Id::new).toList()); + Transcript t = Transcript.start("05-operation-costs.txt", "One call on a PriorityQueue of 1,000,000 elements"); + t.line(String.format("%-28s %14s %14s", "call", "compareTo", "equals")); + calls = equalsCalls = 0; + q.peek(); + t.line(row("peek()", calls, equalsCalls)); + assertEquals(0, calls); + calls = equalsCalls = 0; + q.offer(new Id(-1)); + t.line(row("offer(new smallest)", calls, equalsCalls)); + assertTrue(calls <= 20); + calls = equalsCalls = 0; + q.poll(); + t.line(row("poll()", calls, equalsCalls)); + assertTrue(calls <= 40); + calls = equalsCalls = 0; + assertFalse(q.contains(new Id(-5))); + t.line(row("contains(absent)", calls, equalsCalls)); + assertEquals(n, equalsCalls); + calls = equalsCalls = 0; + assertFalse(q.remove(new Id(-5))); + t.line(row("remove(absent)", calls, equalsCalls)); + assertEquals(n, equalsCalls); + t.flush(); + } + + private static String row(String name, long c, long e) { + return String.format("%-28s %,14d %,14d", name, c, e); + } + + @Test + void tour() { + List out = PriorityQueueTour.run(); + assertTrue(out.contains("min drained = [5, 10, 20, 35, 40, 50]")); + assertTrue(out.contains("poll -> deploy (priority 5, 15 min)")); + Transcript t = Transcript.start("06-priorityqueue-tour.txt", "PriorityQueueTour.run()"); + out.forEach(t::line); + t.flush(); + } + + @Test + void pitfalls() { + List a = Pitfalls.iterationOrder(); + assertEquals("built by add() x 6 : [5, 20, 10, 35, 40, 50]", a.get(0)); + assertEquals("toString() : [5, 10, 35, 20, 40, 50]", a.get(1)); + write("07-iteration-order.txt", "new PriorityQueue<>(List.of(35, 20, 50, 10, 40, 5))", a); + + List b = Pitfalls.subtractionComparator(); + assertTrue(b.get(1).endsWith(": 1")); + assertTrue(b.get(2).endsWith(": -2147483648")); + write("08-subtraction-comparator.txt", "Comparators written with subtraction", b); + + List c = new ArrayList<>(Pitfalls.mutationAfterInsert()); + assertEquals("after c.cost = 1, peek() : A:10", c.get(0)); + assertEquals("remove, change, add, polled : C:1, A:10, B:20", c.get(2)); + c.add(""); + c.addAll(Pitfalls.tiesAreNotFifo()); + write("09-mutation-and-ties.txt", "Mutating a queued element, and equal priorities", c); + + List d = Pitfalls.exceptions(); + assertTrue(d.get(0).contains("NullPointerException")); + assertTrue(d.get(1).contains("ClassCastException")); + assertTrue(d.get(2).contains("IllegalArgumentException")); + assertTrue(d.get(3).contains("ConcurrentModificationException")); + write("10-exceptions.txt", "Calls PriorityQueue rejects", d); + } + + private static void write(String file, String header, List lines) { + Transcript t = Transcript.start(file, header); + lines.forEach(t::line); + t.flush(); + } + + @Test + void heapSort() { + int[] demo = {35, 20, 50, 10, 40, 5}; + Transcript t = Transcript.start("11-heap-sort.txt", "Heap sort of " + Arrays.toString(demo)); + int[] a = demo.clone(); + BinaryHeap built = BinaryHeap.heapify(Arrays.stream(demo).boxed().toList(), Comparator.reverseOrder()); + t.line("after phase 1 (max-heap) : " + built.asList()); + BinaryHeap copy = BinaryHeap.heapify(built.asList(), Comparator.reverseOrder()); + List tail = new ArrayList<>(); + while (!copy.isEmpty()) { + tail.add(0, copy.poll()); + if (!copy.isEmpty()) t.line("heap " + String.format("%-22s", copy.asList()) + " | sorted " + tail); + } + HeapSort.sort(a); + assertArrayEquals(new int[] {5, 10, 20, 35, 40, 50}, a); + t.line("result : " + Arrays.toString(a)); + + Random r = new Random(11); + int trials = 20_000; + for (int i = 0; i < trials; i++) { + int[] x = Data.ints(r, r.nextInt(60), i % 2 == 0 ? 5 : Integer.MAX_VALUE - 1); + int[] y = x.clone(); + HeapSort.sort(x); + Arrays.sort(y); + assertArrayEquals(y, x); + } + t.blank().line("random arrays (seed 11) compared with Arrays.sort : " + trials + ", disagreements: 0"); + t.flush(); + + int n = 100_000; + Transcript c = Transcript.start("12-heap-sort-vs-arrays-sort.txt", "Comparisons to sort n = 100,000 Integers"); + c.line(String.format("%-12s %14s %22s", "input", "HeapSort", "Arrays.sort (TimSort)")); + for (String shape : new String[] {"random", "ascending", "descending"}) { + Integer[] x = Data.sequence(shape, n).toArray(new Integer[0]); + Integer[] y = x.clone(); + Counter h = new Counter<>(Comparator.naturalOrder()); + Counter s = new Counter<>(Comparator.naturalOrder()); + HeapSort.sort(x, h); + Arrays.sort(y, s); + assertArrayEquals(y, x); + assertTrue(h.count > s.count); + c.line(String.format("%-12s %,14d %,22d", shape, h.count, s.count)); + } + c.flush(); + + record Row(String name, int marks) {} + Row[] rows = {new Row("Asha", 70), new Row("Bala", 90), new Row("Chitra", 70), new Row("Dev", 90), new Row("Esha", 70)}; + Row[] byHeap = rows.clone(), byTim = rows.clone(); + HeapSort.sort(byHeap, Comparator.comparingInt(Row::marks)); + Arrays.sort(byTim, Comparator.comparingInt(Row::marks)); + assertNotEquals(Arrays.toString(byTim), Arrays.toString(byHeap)); + Transcript.start("13-heap-sort-not-stable.txt", "Sort by marks only; names were inserted in alphabetical order") + .line("input : " + names(rows)) + .line("HeapSort : " + names(byHeap)) + .line("Arrays.sort : " + names(byTim)) + .flush(); + } + + private static String names(Object[] rows) { + return Arrays.stream(rows).map(o -> o.toString().replaceAll("Row\\[name=(\\w+), marks=(\\d+)]", "$1:$2")).toList().toString(); + } +} diff --git a/heap/src/test/java/com/ankurm/interviewlab/heap/JdkSourceTest.java b/heap/src/test/java/com/ankurm/interviewlab/heap/JdkSourceTest.java new file mode 100644 index 0000000..bcfc0a0 --- /dev/null +++ b/heap/src/test/java/com/ankurm/interviewlab/heap/JdkSourceTest.java @@ -0,0 +1,38 @@ +package com.ankurm.interviewlab.heap; + +import com.ankurm.interviewlab.heap.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import java.util.zip.ZipFile; + +import static org.junit.jupiter.api.Assertions.*; + +/** Quotes java.util.PriorityQueue from the lib/src.zip of the JDK that runs the test. */ +class JdkSourceTest { + + @Test + void quote() throws IOException { + Path zip = Path.of(System.getProperty("java.home"), "lib", "src.zip"); + List src; + try (ZipFile z = new ZipFile(zip.toFile())) { + src = new String(z.getInputStream(z.getEntry("java.base/java/util/PriorityQueue.java")).readAllBytes(), + StandardCharsets.UTF_8).lines().toList(); + } + Transcript t = Transcript.start("23-jdk-source.txt", "java.util.PriorityQueue in JDK " + System.getProperty("java.runtime.version") + " (lib/src.zip)"); + for (String signature : new String[] {"private void grow(int minCapacity)", "public boolean offer(E e)", + "private static void siftUpComparable(", "private void heapify()"}) { + int i = 0; + while (!src.get(i).contains(signature)) i++; + int j = i; + while (!src.get(j).equals(" }")) j++; + for (int n = i; n <= j; n++) t.line(String.format("%4d %s", n + 1, src.get(n))); + t.blank(); + } + assertTrue(src.stream().anyMatch(l -> l.contains("private static void siftDownComparable("))); + t.flush(); + } +} diff --git a/heap/src/test/java/com/ankurm/interviewlab/heap/ProblemsTest.java b/heap/src/test/java/com/ankurm/interviewlab/heap/ProblemsTest.java new file mode 100644 index 0000000..121628a --- /dev/null +++ b/heap/src/test/java/com/ankurm/interviewlab/heap/ProblemsTest.java @@ -0,0 +1,314 @@ +package com.ankurm.interviewlab.heap; + +import com.ankurm.interviewlab.heap.problems.*; +import com.ankurm.interviewlab.heap.problems.MergeKSortedLists.Node; +import com.ankurm.interviewlab.heap.support.Data; +import com.ankurm.interviewlab.heap.support.Data.Counter; +import com.ankurm.interviewlab.heap.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; + +class ProblemsTest { + + @Test + void kthLargest() { + int[] a = {3, 2, 3, 1, 2, 4, 5, 5, 6}; + assertEquals(4, KthLargest.find(a, 4)); + Transcript t = Transcript.start("14-kth-largest.txt", "Problem 1 and 2: k-th largest"); + t.line("array " + Arrays.toString(a) + " k = 4 -> " + KthLargest.find(a, 4)); + KthLargestStream s = new KthLargestStream(3, new int[] {4, 5, 8, 2}); + List got = new ArrayList<>(); + for (int v : new int[] {3, 5, 10, 9, 4}) got.add("add(" + v + ")=" + s.add(v)); + assertEquals("[add(3)=4, add(5)=5, add(10)=5, add(9)=8, add(4)=8]", got.toString()); + t.blank().line("stream, k = 3, starting with [4, 5, 8, 2]:").line(" " + String.join(" ", got)); + t.flush(); + } + + /** The three ways to get the k largest, counted. */ + @Test + void topKComparisonCounts() { + int n = 1_000_000; + Transcript t = Transcript.start("15-top-k-comparisons.txt", "The k largest of n = 1,000,000 distinct ints: comparisons"); + t.line(String.format("%-12s %9s %20s %20s %24s", "input", "k", "sort everything", "min-heap of size k", "max-heap all, poll k")); + for (int k : new int[] {10, 1_000, 500_000}) { + for (String shape : new String[] {"random", "ascending", "descending"}) { + List items = Data.sequence(shape, n); + Counter sort = new Counter<>(Comparator.naturalOrder()); + Integer[] copy = items.toArray(new Integer[0]); + Arrays.sort(copy, sort); + + Counter small = new Counter<>(Comparator.naturalOrder()); + PriorityQueue top = new PriorityQueue<>(small); + for (Integer x : items) { + if (top.size() < k) top.offer(x); + else if (small.compare(x, top.peek()) > 0) { + top.poll(); + top.offer(x); + } + } + Counter all = new Counter<>(Comparator.reverseOrder()); + BinaryHeap max = BinaryHeap.heapify(items, all); + int last = 0; + for (int i = 0; i < k; i++) last = max.poll(); + assertEquals(copy[n - k], last); + assertEquals(copy[n - k], top.peek()); + t.line(String.format("%-12s %,9d %,20d %,20d %,24d", shape, k, sort.count, small.count, all.count)); + } + } + t.flush(); + } + + @Test + void topKFrequent() { + int[] a = {1, 1, 1, 2, 2, 3, 4, 4, 4, 4}; + assertEquals(List.of(4, 1), TopKFrequent.byHeap(a, 2)); + assertEquals(List.of(4, 1), TopKFrequent.byBuckets(a, 2)); + String[] w = {"java", "heap", "queue", "java", "heap", "tree", "queue", "array"}; + assertEquals(List.of("heap", "java"), TopKFrequent.words(w, 2)); + List wrong = TopKFrequent.wordsWithWrongTieBreak(w, 2); + assertNotEquals(List.of("heap", "java"), wrong); + Transcript.start("16-top-k-frequent.txt", "Problem 3: top k frequent") + .line("nums " + Arrays.toString(a) + " k = 2") + .line(" heap : " + TopKFrequent.byHeap(a, 2)) + .line(" buckets : " + TopKFrequent.byBuckets(a, 2)) + .blank() + .line("words " + Arrays.toString(w) + " k = 2 (java, heap and queue all occur twice)") + .line(" tie-break reversed inside the worst-first heap : " + TopKFrequent.words(w, 2)) + .line(" tie-break NOT reversed (the bug) : " + wrong) + .flush(); + } + + @Test + void closestPointsAndStones() { + int[][] p = {{3, 3}, {5, -1}, {-2, 4}}; + List got = KClosestPoints.find(p, 2); + String shown = got.stream().map(Arrays::toString).sorted().toList().toString(); + assertEquals("[[-2, 4], [3, 3]]", shown); + int x = 50_000; + int wrong = x * x + 0; + long right = KClosestPoints.distance(new int[] {x, 0}); + assertTrue(wrong < 0); + int[] stones = {2, 7, 4, 1, 8, 1}; + assertEquals(1, LastStoneWeight.solve(stones)); + Transcript.start("17-closest-points-and-stones.txt", "Problem 4 and 5") + .line("points [3,3] [5,-1] [-2,4], k = 2 -> " + shown) + .line("point (50000, 0): squared distance in int = " + wrong) + .line("point (50000, 0): squared distance in long = " + right) + .blank() + .line("stones " + Arrays.toString(stones) + " -> last stone weight " + LastStoneWeight.solve(stones)) + .flush(); + } + + @Test + void mergeK() { + int[][] small = {{1, 4, 5}, {1, 3, 4}, {2, 6}, {}}; + int[] merged = Data.values(MergeKSortedLists.merge(Data.lists(small))); + assertArrayEquals(new int[] {1, 1, 2, 3, 4, 4, 5, 6}, merged); + Transcript t = Transcript.start("18-merge-k-sorted-lists.txt", "Problem 6: merge k sorted lists"); + t.line("[1,4,5] [1,3,4] [2,6] [] -> " + Arrays.toString(merged)); + try { + new PriorityQueue(Comparator.comparingInt(n -> n.val)).offer(null); + fail(); + } catch (NullPointerException e) { + t.line("offering the head of an empty list (null) without the check: " + e.getClass().getSimpleName()); + } + t.blank().line("comparisons, each list holding 1,000 random values (seed 5):"); + t.line(String.format("%6s %10s %16s %18s %16s", "k", "N", "heap of heads", "merge one by one", "merge in pairs")); + for (int k : new int[] {2, 10, 100, 1000}) { + Random r = new Random(5); + int[][] arrays = new int[k][]; + for (int i = 0; i < k; i++) { + arrays[i] = Data.ints(r, 1000, 1_000_000); + Arrays.sort(arrays[i]); + } + int[] expected = BruteForce.flattenAndSort(arrays); + Counter heap = new Counter<>(Comparator.comparingInt(n -> n.val)); + Counter one = new Counter<>(Comparator.comparingInt(n -> n.val)); + Counter pairs = new Counter<>(Comparator.comparingInt(n -> n.val)); + assertArrayEquals(expected, Data.values(MergeKSortedLists.merge(Data.lists(arrays), heap))); + assertArrayEquals(expected, Data.values(MergeKSortedLists.mergeOneByOne(Data.lists(arrays), one))); + assertArrayEquals(expected, Data.values(MergeKSortedLists.mergeInPairs(Data.lists(arrays), pairs))); + t.line(String.format("%,6d %,10d %,16d %,18d %,16d", k, k * 1000, heap.count, one.count, pairs.count)); + } + t.flush(); + } + + @Test + void runningMedian() { + RunningMedian m = new RunningMedian(); + Transcript t = Transcript.start("19-running-median.txt", "Problem 7: median of a stream"); + List medians = new ArrayList<>(); + for (int v : new int[] {5, 15, 1, 3, 8, 7}) { + m.add(v); + medians.add(m.median()); + t.line(String.format("add(%2d) %-52s median=%s", v, m.halves(), m.median())); + } + assertEquals(List.of(5.0, 10.0, 5.0, 4.0, 5.0, 6.0), medians); + RunningMedian big = new RunningMedian(); + big.add(Integer.MAX_VALUE); + big.add(Integer.MAX_VALUE - 2); + assertEquals(2147483646.0, big.median()); + double overflowed = (Integer.MAX_VALUE + (Integer.MAX_VALUE - 2)) / 2.0; + t.blank().line("values 2147483647 and 2147483645:") + .line(" (a + b) / 2.0 in int arithmetic : " + overflowed) + .line(" ((long) a + b) / 2.0 : " + String.format("%.1f", big.median())); + t.flush(); + } + + @Test + void taskScheduler() { + Transcript t = Transcript.start("20-task-scheduler.txt", "Problem 8: task scheduler ('.' = idle)"); + String[][] cases = {{"AAABBB", "2"}, {"AAABBB", "0"}, {"AAAAAABCDEFG", "2"}, {"AAABBBCCCDD", "2"}}; + for (String[] c : cases) { + int n = Integer.parseInt(c[1]); + String s = TaskScheduler.schedule(c[0], n); + assertEquals(TaskScheduler.formula(c[0], n), s.length()); + assertEquals(BruteForce.shortestSchedule(c[0], n), s.length()); + t.line(String.format("tasks=%-13s n=%d timeline=%-18s length=%d formula=%d", c[0], n, s, s.length(), TaskScheduler.formula(c[0], n))); + } + assertEquals("AB.AB.AB", TaskScheduler.schedule("AAABBB", 2)); + t.flush(); + } + + @Test + void roomsAndRopes() { + int[][] m = {{0, 30}, {5, 10}, {15, 20}}; + assertEquals(2, MeetingRooms.minRooms(m)); + int[][] touching = {{9, 10}, {10, 11}, {11, 12}}; + assertEquals(1, MeetingRooms.minRooms(touching)); + int[] r = {4, 3, 2, 6}; + assertEquals(29, ConnectRopes.minCost(r)); + int[] four = {4, 4, 4, 4}; + assertEquals(32, ConnectRopes.minCost(four)); + assertEquals(36, ConnectRopes.sortOnceAndFold(four)); + Transcript.start("21-meeting-rooms-and-ropes.txt", "Problem 9 and 10") + .line("meetings [0,30) [5,10) [15,20) -> rooms " + MeetingRooms.minRooms(m)) + .line("meetings [9,10) [10,11) [11,12) -> rooms " + MeetingRooms.minRooms(touching)) + .blank() + .line("ropes " + Arrays.toString(r) + " heap: " + ConnectRopes.minCost(r) + " sort once and fold: " + ConnectRopes.sortOnceAndFold(r)) + .line("ropes " + Arrays.toString(four) + " heap: " + ConnectRopes.minCost(four) + " sort once and fold: " + ConnectRopes.sortOnceAndFold(four)) + .flush(); + } + + @Test + void crossCheckEverythingAgainstBruteForce() { + Transcript t = Transcript.start("22-brute-force-cross-checks.txt", "Heap solutions vs brute force on seeded random input (seed 2026)"); + t.line(String.format("%-34s %8s %14s", "problem", "trials", "disagreements")); + Random r = new Random(2026); + + for (int i = 0; i < 5000; i++) { + int[] a = Data.ints(r, 1 + r.nextInt(40), 15); + int k = 1 + r.nextInt(a.length); + assertEquals(BruteForce.kthLargest(a, k), KthLargest.find(a, k)); + } + row(t, "1 k-th largest", 5000); + + for (int i = 0; i < 2000; i++) { + int k = 1 + r.nextInt(6); + KthLargestStream s = new KthLargestStream(k, new int[0]); + int[] a = Data.ints(r, 30, 20); + for (int j = 0; j < a.length; j++) { + Integer got = s.add(a[j]); + if (j + 1 < k) assertNull(got); + else assertEquals(BruteForce.kthLargest(Arrays.copyOf(a, j + 1), k), got); + } + } + row(t, "2 k-th largest in a stream", 2000); + + for (int i = 0; i < 5000; i++) { + int[] a = Data.ints(r, 1 + r.nextInt(40), 6); + int k = 1 + r.nextInt(5); + List expected = BruteForce.topKFrequent(a, k); + assertEquals(expected, TopKFrequent.byHeap(a, k)); + assertEquals(expected, TopKFrequent.byBuckets(a, k)); + } + row(t, "3 top k frequent (heap, buckets)", 5000); + + for (int i = 0; i < 5000; i++) { + int[][] p = new int[1 + r.nextInt(30)][]; + for (int j = 0; j < p.length; j++) p[j] = Data.ints(r, 2, i % 2 == 0 ? 5 : 100_000); + int k = 1 + r.nextInt(p.length); + long[] got = KClosestPoints.find(p, k).stream().mapToLong(KClosestPoints::distance).sorted().toArray(); + assertArrayEquals(BruteForce.kClosestDistances(p, k), got); + } + row(t, "4 k closest points", 5000); + + for (int i = 0; i < 5000; i++) { + int[] a = r.ints(1 + r.nextInt(20), 1, 100).toArray(); + assertEquals(BruteForce.lastStone(a), LastStoneWeight.solve(a)); + } + row(t, "5 last stone weight", 5000); + + for (int i = 0; i < 3000; i++) { + int[][] lists = new int[r.nextInt(8)][]; + for (int j = 0; j < lists.length; j++) { + lists[j] = Data.ints(r, r.nextInt(10), 20); + Arrays.sort(lists[j]); + } + assertArrayEquals(BruteForce.flattenAndSort(lists), Data.values(MergeKSortedLists.merge(Data.lists(lists)))); + } + row(t, "6 merge k sorted lists", 3000); + + for (int i = 0; i < 1000; i++) { + int[] a = Data.ints(r, 1 + r.nextInt(60), i % 2 == 0 ? 10 : Integer.MAX_VALUE - 1); + RunningMedian m = new RunningMedian(); + for (int j = 0; j < a.length; j++) { + m.add(a[j]); + assertEquals(BruteForce.median(a, j + 1), m.median()); + } + } + row(t, "7 running median", 1000); + + for (int i = 0; i < 1500; i++) { + StringBuilder s = new StringBuilder(); + int len = 1 + r.nextInt(8); + for (int j = 0; j < len; j++) s.append((char) ('A' + r.nextInt(4))); + int n = r.nextInt(4); + String timeline = TaskScheduler.schedule(s.toString(), n); + assertEquals(BruteForce.shortestSchedule(s.toString(), n), timeline.length(), s + " n=" + n); + assertEquals(timeline.length(), TaskScheduler.formula(s.toString(), n)); + assertValid(s.toString(), n, timeline); + } + row(t, "8 task scheduler (vs search)", 1500); + + for (int i = 0; i < 5000; i++) { + int[][] m = new int[r.nextInt(15)][]; + for (int j = 0; j < m.length; j++) { + int s = r.nextInt(30); + m[j] = new int[] {s, s + 1 + r.nextInt(10)}; + } + assertEquals(BruteForce.minRooms(m), MeetingRooms.minRooms(m)); + } + row(t, "9 meeting rooms", 5000); + + int foldWrong = 0; + for (int i = 0; i < 1000; i++) { + int[] a = r.ints(1 + r.nextInt(7), 1, 50).toArray(); + long best = BruteForce.minRopeCost(Arrays.stream(a).asLongStream().toArray()); + assertEquals(best, ConnectRopes.minCost(a)); + if (ConnectRopes.sortOnceAndFold(a) != best) foldWrong++; + } + row(t, "10 connect ropes (vs all pairings)", 1000); + assertTrue(foldWrong > 0); + t.blank().line("the sort-once-and-fold shortcut was wrong on " + foldWrong + " of those 1000 rope sets"); + t.flush(); + } + + private static void row(Transcript t, String name, int trials) { + t.line(String.format("%-34s %8d %14d", name, trials, 0)); + } + + private static void assertValid(String tasks, int n, String timeline) { + char[] a = tasks.toCharArray(); + char[] b = timeline.replace(".", "").toCharArray(); + Arrays.sort(a); + Arrays.sort(b); + assertArrayEquals(a, b); + for (int i = 0; i < timeline.length(); i++) + for (int j = i + 1; j <= Math.min(timeline.length() - 1, i + n); j++) + if (timeline.charAt(i) != '.') assertNotEquals(timeline.charAt(i), timeline.charAt(j)); + } +} diff --git a/heap/src/test/java/com/ankurm/interviewlab/heap/support/Data.java b/heap/src/test/java/com/ankurm/interviewlab/heap/support/Data.java new file mode 100644 index 0000000..74f42c9 --- /dev/null +++ b/heap/src/test/java/com/ankurm/interviewlab/heap/support/Data.java @@ -0,0 +1,58 @@ +package com.ankurm.interviewlab.heap.support; + +import com.ankurm.interviewlab.heap.problems.MergeKSortedLists.Node; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Random; + +/** Seeded inputs and a comparison counter, so every figure is reproducible. */ +public final class Data { + private Data() {} + + public static final class Counter implements Comparator { + private final Comparator inner; + public long count; + + public Counter(Comparator inner) { this.inner = inner; } + + @Override public int compare(T a, T b) { + count++; + return inner.compare(a, b); + } + } + + public static int[] ints(Random r, int n, int bound) { + return r.ints(n, -bound, bound + 1).toArray(); + } + + public static List sequence(String shape, int n) { + List list = new ArrayList<>(n); + for (int i = 0; i < n; i++) list.add(i); + if (shape.equals("descending")) Collections.reverse(list); + if (shape.equals("random")) Collections.shuffle(list, new Random(42)); + return list; + } + + public static Node list(int[] sorted) { + Node dummy = new Node(0), tail = dummy; + for (int v : sorted) { + tail.next = new Node(v); + tail = tail.next; + } + return dummy.next; + } + + public static Node[] lists(int[][] arrays) { + return Arrays.stream(arrays).map(Data::list).toArray(Node[]::new); + } + + public static int[] values(Node n) { + List out = new ArrayList<>(); + for (; n != null; n = n.next) out.add(n.val); + return out.stream().mapToInt(Integer::intValue).toArray(); + } +} diff --git a/heap/src/test/java/com/ankurm/interviewlab/heap/support/Transcript.java b/heap/src/test/java/com/ankurm/interviewlab/heap/support/Transcript.java new file mode 100644 index 0000000..0135a53 --- /dev/null +++ b/heap/src/test/java/com/ankurm/interviewlab/heap/support/Transcript.java @@ -0,0 +1,43 @@ +package com.ankurm.interviewlab.heap.support; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */ +public final class Transcript { + private final Path path; + private final List lines = new ArrayList<>(); + + private Transcript(Path path, String header) { + this.path = path; + lines.add(header); + lines.add("=".repeat(Math.min(header.length(), 100))); + lines.add(""); + } + + public static Transcript start(String fileName, String header) { + Path dir = Path.of("output"); + try { + Files.createDirectories(dir); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new Transcript(dir.resolve(fileName), header); + } + + public Transcript line(String text) { lines.add(text); return this; } + public Transcript blank() { lines.add(""); return this; } + + public void flush() { + try { + Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +}