diff --git a/README.md b/README.md index f4ca2a6..7f38564 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ One module per article. This repository currently holds: | [`notification-service`](notification-service/) | System Design: Notification Service with Spring Boot and Kafka (Email, SMS, Push) | this commit | | [`linked-list`](linked-list/) | Linked List in Java: Singly, Doubly, Reverse, Cycle Detection and Interview Problems | this commit | | [`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 | ## `collections` module diff --git a/bst/README.md b/bst/README.md new file mode 100644 index 0000000..1bb5c79 --- /dev/null +++ b/bst/README.md @@ -0,0 +1,56 @@ +# bst + +Companion code for the ankurm.com article **Binary Search Tree in Java: Insert, Delete, Search, Validate BST and LCA (With Dry Runs)**. + +Insert and search (recursive and iterative), the three delete cases, three broken variants, BST validation, kth smallest, lowest common +ancestor, floor/ceiling, height and balance, and ten interview problems checked against brute force on seeded random trees. 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 | Verified against | +|---|---|---| +| JDK | Temurin 25.0.5.1+2 (LTS) | `java -version` | +| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA) | +| Maven | 3.9.11 | `mvn -version` | + +## Quickstart + +```bash +cd bst +export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH" +./scripts/run-all.sh # runs 25 tests and regenerates output/*.txt +java -cp target/classes com.ankurm.interviewlab.bst.DeepTreeDemo 100000 +``` + +The first Maven run must be online so the plugins land in the local cache. + +## Source layout + +| File (`src/main/java/com/ankurm/interviewlab/bst/`) | Contents | +|---|---| +| `Node.java` | key plus two child links | +| `Insert.java`, `Search.java`, `Delete.java` | recursive and iterative versions; min and max | +| `Validate.java` | two wrong checks, the min/max-bounds check, the inorder check | +| `Queries.java` | kth smallest, LCA, floor, ceiling, inorder | +| `Balance.java` | height, two balance checks with visit counters | +| `Problems.java` | interview problems 4 to 10 | +| `Mistakes.java` | lost insert, delete that leaves a duplicate | +| `TreePrinter.java`, `DeepTreeDemo.java` | tree outline; recursion on a 100,000-node chain | + +Tests: `DryRunTest` (transcripts 01-10), `ShapeTest` (11-14), `CrossCheckTest` (15-16). + +## Captured output + +| File | What it shows | +|---|---| +| `01` to `05` | insert, search and the three delete cases, step by step | +| `06-mistakes.txt` | lost insert, ignored return value, duplicate left by a half-finished delete | +| `07-validate.txt` | children-only check fooled; int sentinels rejecting `Integer.MIN_VALUE` / `MAX_VALUE` | +| `08` to `10` | kth smallest, LCA, floor and ceiling traces | +| `11-insertion-order.txt` | height and average search cost for sorted, shuffled and middle-first insertion | +| `12-treeset-sorted-input.txt` | comparisons in `java.util.TreeSet` fed sorted keys | +| `13-balance-visits.txt` | node visits of the two balance checks, including the shape that hurts the top-down one | +| `14-deep-chain.txt` | `StackOverflowError` from recursive search; the loop returns (depth depends on stack size) | +| `15`, `16` | random operations against `TreeSet`; ten problems against brute force | diff --git a/bst/output/01-insert-dry-run.txt b/bst/output/01-insert-dry-run.txt new file mode 100644 index 0000000..67c107f --- /dev/null +++ b/bst/output/01-insert-dry-run.txt @@ -0,0 +1,26 @@ +Insert 50 30 70 20 40 60 80 35 65, one key at a time +==================================================== + +insert 50: -> becomes the root +insert 30: 50 L -> new left child of 50 +insert 70: 50 R -> new right child of 50 +insert 20: 50 L, 30 L -> new left child of 30 +insert 40: 50 L, 30 R -> new right child of 30 +insert 60: 50 R, 70 L -> new left child of 70 +insert 80: 50 R, 70 R -> new right child of 70 +insert 35: 50 L, 30 R, 40 L -> new left child of 40 +insert 65: 50 R, 70 L, 60 R -> new right child of 60 +insert 40 again: no change (set semantics), still 9 nodes + +Tree (recursive and iterative insert give the same outline): +50 + L: 30 + L: 20 + R: 40 + L: 35 + R: 70 + L: 60 + R: 65 + R: 80 + +inorder: [20, 30, 35, 40, 50, 60, 65, 70, 80] diff --git a/bst/output/02-search-dry-run.txt b/bst/output/02-search-dry-run.txt new file mode 100644 index 0000000..dbfbb9d --- /dev/null +++ b/bst/output/02-search-dry-run.txt @@ -0,0 +1,15 @@ +Search the sample tree +====================== + +search 65: + at 50: 65 > 50, go right + at 70: 65 < 70, go left + at 60: 65 > 60, go right + at 65: equal, found after 4 nodes +search 45: + at 50: 45 < 50, go left + at 30: 45 > 30, go right + at 40: 45 > 40, go right + null reached after 3 nodes: 45 is not in the tree + +min = 20 (keep going left), max = 80 (keep going right) diff --git a/bst/output/03-delete-leaf.txt b/bst/output/03-delete-leaf.txt new file mode 100644 index 0000000..37b57b1 --- /dev/null +++ b/bst/output/03-delete-leaf.txt @@ -0,0 +1,31 @@ +Delete case 1: a leaf +===================== + +before: +50 + L: 30 + L: 20 + R: 40 + L: 35 + R: 70 + L: 60 + R: 65 + R: 80 + +delete 20: + at 50: 20 < 50, go left + at 30: 20 < 30, go left + at 20: equal, found after 3 nodes + leaf: return null to the parent + +after: +50 + L: 30 + R: 40 + L: 35 + R: 70 + L: 60 + R: 65 + R: 80 + +inorder: [30, 35, 40, 50, 60, 65, 70, 80] diff --git a/bst/output/04-delete-one-child.txt b/bst/output/04-delete-one-child.txt new file mode 100644 index 0000000..07e929f --- /dev/null +++ b/bst/output/04-delete-one-child.txt @@ -0,0 +1,31 @@ +Delete case 2: a node with one child +==================================== + +before: +50 + L: 30 + L: 20 + R: 40 + L: 35 + R: 70 + L: 60 + R: 65 + R: 80 + +delete 60: + at 50: 60 > 50, go right + at 70: 60 < 70, go left + at 60: equal, found after 3 nodes + one child (65): return that child to the parent + +after: +50 + L: 30 + L: 20 + R: 40 + L: 35 + R: 70 + L: 65 + R: 80 + +inorder: [20, 30, 35, 40, 50, 65, 70, 80] diff --git a/bst/output/05-delete-two-children.txt b/bst/output/05-delete-two-children.txt new file mode 100644 index 0000000..910e748 --- /dev/null +++ b/bst/output/05-delete-two-children.txt @@ -0,0 +1,30 @@ +Delete case 3: a node with two children (the root) +================================================== + +before: +50 + L: 30 + L: 20 + R: 40 + L: 35 + R: 70 + L: 60 + R: 65 + R: 80 + +delete 50: + at 50: equal, found after 1 nodes + two children: successor = smallest key in right subtree = 60 + copy 60 into the node, then delete 60 from the right subtree + +after: +60 + L: 30 + L: 20 + R: 40 + L: 35 + R: 70 + L: 65 + R: 80 + +inorder: [20, 30, 35, 40, 60, 65, 70, 80] diff --git a/bst/output/06-mistakes.txt b/bst/output/06-mistakes.txt new file mode 100644 index 0000000..51baff0 --- /dev/null +++ b/bst/output/06-mistakes.txt @@ -0,0 +1,13 @@ +Two broken variants, run +======================== + +insertLost(root, 45), then search 45: false +inorder: [20, 30, 35, 40, 50, 60, 65, 70, 80] + +tree 50,70: Delete.recursive(root, 50) with the result thrown away + inorder from the old root variable: [50, 70] + root = Delete.recursive(root, 50): [70] + +deleteLeavesDuplicate(sample, 50) + inorder: [20, 30, 35, 40, 60, 60, 65, 70, 80] + isBst: false diff --git a/bst/output/07-validate.txt b/bst/output/07-validate.txt new file mode 100644 index 0000000..8e89d46 --- /dev/null +++ b/bst/output/07-validate.txt @@ -0,0 +1,24 @@ +Validate BST: the children-only check, the bounds check, the sentinel trap +========================================================================== + +A tree where 55 sits in the LEFT subtree of 50: +50 + L: 30 + L: 20 + R: 55 + R: 70 + L: 60 + R: 80 + +childrenOnly: true +isBst: false +byInorder: false inorder = [20, 30, 55, 50, 60, 70, 80] + +Bounds trace (stops at the first violation): + node 50 allowed (-inf, +inf) ok + node 30 allowed (-inf, 50) ok + node 20 allowed (-inf, 30) ok + node 55 allowed (30, 50) VIOLATION + +single node 2147483647: intSentinels=false isBst=true +single node -2147483648: intSentinels=false isBst=true diff --git a/bst/output/08-kth-smallest.txt b/bst/output/08-kth-smallest.txt new file mode 100644 index 0000000..248a6f6 --- /dev/null +++ b/bst/output/08-kth-smallest.txt @@ -0,0 +1,14 @@ +kth smallest, k = 4, on the sample tree: stack after each step +============================================================== + +push 50 stack (top first) [50] +push 30 stack (top first) [30, 50] +push 20 stack (top first) [20, 30, 50] +pop 20 stack (top first) [30, 50] k left 3 +pop 30 stack (top first) [50] k left 2 +push 40 stack (top first) [40, 50] +push 35 stack (top first) [35, 40, 50] +pop 35 stack (top first) [40, 50] k left 1 +pop 40 stack (top first) [50] k left 0 + +answer: 40 diff --git a/bst/output/09-lca.txt b/bst/output/09-lca.txt new file mode 100644 index 0000000..fc94097 --- /dev/null +++ b/bst/output/09-lca.txt @@ -0,0 +1,14 @@ +Lowest common ancestor on the sample tree +========================================= + +lca(20, 35): + at 50: both smaller, go left + at 30: paths split here, answer 30 +lca(35, 65): + at 50: paths split here, answer 50 +lca(60, 65): + at 50: both larger, go right + at 70: both smaller, go left + at 60: paths split here, answer 60 + +lca(20, 99), with 99 absent, returns 50 (a wrong-looking answer: check presence first) diff --git a/bst/output/10-floor-ceiling.txt b/bst/output/10-floor-ceiling.txt new file mode 100644 index 0000000..37c64e8 --- /dev/null +++ b/bst/output/10-floor-ceiling.txt @@ -0,0 +1,15 @@ +floor and ceiling of 45 on the sample tree: the best candidate so far +===================================================================== + +floor(45): + at 50: too big, best = none, go left + at 30: candidate, best = 30, go right + at 40: candidate, best = 40, go right + answer 40 +ceiling(45): + at 50: candidate, best = 50, go left + at 30: too small, best = 50, go right + at 40: too small, best = 50, go right + answer 50 + +floor(10) = OptionalInt.empty, ceiling(90) = OptionalInt.empty diff --git a/bst/output/11-insertion-order.txt b/bst/output/11-insertion-order.txt new file mode 100644 index 0000000..baff4f0 --- /dev/null +++ b/bst/output/11-insertion-order.txt @@ -0,0 +1,11 @@ +Same keys, different insertion order (n = 1023; shuffles seeded 1..5) +===================================================================== + +order height avg nodes per search +sorted 1..1023 1023 512.00 +shuffled, seed 1 24 11.58 +shuffled, seed 2 19 11.47 +shuffled, seed 3 20 11.81 +shuffled, seed 4 23 12.15 +shuffled, seed 5 25 12.98 +middle-first (fromSorted) 10 9.01 diff --git a/bst/output/12-treeset-sorted-input.txt b/bst/output/12-treeset-sorted-input.txt new file mode 100644 index 0000000..b8f0528 --- /dev/null +++ b/bst/output/12-treeset-sorted-input.txt @@ -0,0 +1,5 @@ +java.util.TreeSet fed sorted keys, comparisons counted by its Comparator +======================================================================== + +n = 1023 contains(): worst 18 comparisons, average 9.51 (plain BST on the same input: worst 1023, average 512.0) +n = 100000 contains(): worst 31 comparisons, average 16.10 (plain BST on the same input: worst 100000, average 50000.5) diff --git a/bst/output/13-balance-visits.txt b/bst/output/13-balance-visits.txt new file mode 100644 index 0000000..3d9337f --- /dev/null +++ b/bst/output/13-balance-visits.txt @@ -0,0 +1,13 @@ +isBalanced: height recomputed at every node versus one postorder pass (node visits) +=================================================================================== + +sample tree: height 4, balanced true + +tree balanced top-down one pass +perfect, n = 1023 true 8194 1023 +perfect, n = 16383 true 196610 16383 +chain, n = 1000 false 999 1000 +chain, n = 2000 false 1999 2000 +comb 100, n = 5050 false 171603 106 +comb 200, n = 20100 false 1353203 206 +comb 400, n = 80200 false 10746403 406 diff --git a/bst/output/14-deep-chain.txt b/bst/output/14-deep-chain.txt new file mode 100644 index 0000000..d03d61c --- /dev/null +++ b/bst/output/14-deep-chain.txt @@ -0,0 +1,6 @@ +Recursion depth equals tree height +================================== + +chain of 100000 nodes, 512 KB thread stack +Search.recursive: threw java.lang.StackOverflowError +Search.iterative: returned true diff --git a/bst/output/15-random-operations.txt b/bst/output/15-random-operations.txt new file mode 100644 index 0000000..07dc972 --- /dev/null +++ b/bst/output/15-random-operations.txt @@ -0,0 +1,6 @@ +insert, delete, search, floor, ceiling against java.util.TreeSet (seed 42) +========================================================================== + +20000 random steps (10028 inserts, 9972 deletes), checked after every step: + inorder equals the TreeSet, isBst is true, recursive and iterative trees have identical shape, + search, floor and ceiling give the TreeSet's answers diff --git a/bst/output/16-ten-problems.txt b/bst/output/16-ten-problems.txt new file mode 100644 index 0000000..46ad005 --- /dev/null +++ b/bst/output/16-ten-problems.txt @@ -0,0 +1,13 @@ +Ten problems, each against a brute force on random trees (seeded) +================================================================= + + 1. validate BST: 20000 random binary trees, 7382 were BSTs; bounds and inorder agreed on all; childrenOnly wrongly accepted 417 + 2. kth smallest: 27427 (tree, k) cases against sorting all keys + 3. lowest common ancestor: 18990 pairs against comparing the two root paths + 4. range sum: 2000 cases against filtering all keys; sample tree [35, 50] = 125 + 5. sorted array to balanced BST: every n from 0 to 500 is a balanced BST of minimum height with the same keys + 6. inorder successor: 2000 cases against scanning all keys; successor(40) in the sample tree = 50 + 7. two keys summing to a target: 2000 cases (359 true) against all pairs + 8. minimum difference: 1729 trees against all pairs; MIN_VALUE and MAX_VALUE give 4294967295 (needs long) + 9. recover two swapped keys: 1834 damaged trees, all restored +10. trim to a range: 2000 cases against filtering all keys, result still a BST; sample trimmed to [35, 65] = [35, 40, 50, 60, 65] diff --git a/bst/pom.xml b/bst/pom.xml new file mode 100644 index 0000000..70971dd --- /dev/null +++ b/bst/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + com.ankurm.interviewlab + bst + 1.0.0 + jar + + java-interview-lab :: bst + + Runnable companion code for ankurm.com's "Binary Search Tree in Java" article: insert and search (recursive and + iterative), the three delete cases, validation, kth smallest, LCA, floor/ceil, balance check and 10 problems. + + + + 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/bst/scripts/run-all.sh b/bst/scripts/run-all.sh new file mode 100755 index 0000000..38df9a6 --- /dev/null +++ b/bst/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/bst/src/main/java/com/ankurm/interviewlab/bst/Balance.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Balance.java new file mode 100644 index 0000000..df5851a --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Balance.java @@ -0,0 +1,47 @@ +package com.ankurm.interviewlab.bst; + +/** Height and height-balance. Height counts nodes on the longest root-to-leaf path (empty tree = 0). */ +public final class Balance { + private Balance() {} + + public static int height(Node node) { + if (node == null) return 0; + return 1 + Math.max(height(node.left), height(node.right)); + } + + /** Counts node visits so the two balance checks can be compared without a stopwatch. */ + public static final class Counter { + public long visits; + } + + /** + * Asks for the height again at every node: O(n log n) on a balanced tree. Because it returns at the + * first failure, a plain chain costs only about n; the bad shapes are balanced near the top only. + */ + public static boolean isBalancedTopDown(Node node, Counter c) { + if (node == null) return true; + if (Math.abs(countedHeight(node.left, c) - countedHeight(node.right, c)) > 1) return false; + return isBalancedTopDown(node.left, c) && isBalancedTopDown(node.right, c); + } + + private static int countedHeight(Node node, Counter c) { + if (node == null) return 0; + c.visits++; + return 1 + Math.max(countedHeight(node.left, c), countedHeight(node.right, c)); + } + + /** One postorder pass; -1 means "already unbalanced below here": O(n). */ + public static boolean isBalanced(Node root, Counter c) { + return check(root, c) >= 0; + } + + private static int check(Node node, Counter c) { + if (node == null) return 0; + c.visits++; + int left = check(node.left, c); + if (left < 0) return -1; + int right = check(node.right, c); + if (right < 0 || Math.abs(left - right) > 1) return -1; + return 1 + Math.max(left, right); + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/DeepTreeDemo.java b/bst/src/main/java/com/ankurm/interviewlab/bst/DeepTreeDemo.java new file mode 100644 index 0000000..1a70c7d --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/DeepTreeDemo.java @@ -0,0 +1,44 @@ +package com.ankurm.interviewlab.bst; + +import java.util.concurrent.atomic.AtomicReference; + +/** + * A chain is what sorted inserts produce. The chain here is linked directly (building it through + * insert would cost n^2/2 comparisons), then searched both ways on a thread with a 512 KB stack. + */ +public final class DeepTreeDemo { + private DeepTreeDemo() {} + + public static Node chain(int n) { + Node root = new Node(1); + Node tail = root; + for (int key = 2; key <= n; key++) { + tail.right = new Node(key); + tail = tail.right; + } + return root; + } + + public static String run(int n) throws InterruptedException { + Node root = chain(n); + var report = new AtomicReference(); + Thread t = new Thread(null, () -> { + String recursive; + try { + recursive = "returned " + Search.recursive(root, n); + } catch (StackOverflowError e) { + recursive = "threw java.lang.StackOverflowError"; + } + report.set("chain of " + n + " nodes, 512 KB thread stack\n" + + "Search.recursive: " + recursive + "\n" + + "Search.iterative: returned " + Search.iterative(root, n)); + }, "small-stack", 512 * 1024); + t.start(); + t.join(); + return report.get(); + } + + public static void main(String[] args) throws InterruptedException { + System.out.println(run(args.length > 0 ? Integer.parseInt(args[0]) : 100_000)); + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/Delete.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Delete.java new file mode 100644 index 0000000..098206b --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Delete.java @@ -0,0 +1,58 @@ +package com.ankurm.interviewlab.bst; + +/** Delete: leaf, one child, two children. Deleting an absent key changes nothing. */ +public final class Delete { + private Delete() {} + + /** Returns the root of the subtree after the delete. The caller MUST store the result. */ + public static Node recursive(Node node, int key) { + if (node == null) return null; + if (key < node.key) { + node.left = recursive(node.left, key); + } else if (key > node.key) { + node.right = recursive(node.right, key); + } else { + if (node.left == null) return node.right; // leaf (returns null) or only a right child + if (node.right == null) return node.left; // only a left child + Node successor = Search.min(node.right); // two children: smallest key on the right + node.key = successor.key; + node.right = recursive(node.right, successor.key); + } + return node; + } + + /** The same three cases with loops. It relinks the successor node instead of copying its key. */ + public static Node iterative(Node root, int key) { + Node parent = null; + Node target = root; + while (target != null && target.key != key) { + parent = target; + target = key < target.key ? target.left : target.right; + } + if (target == null) return root; + + Node replacement; + if (target.left == null) { + replacement = target.right; + } else if (target.right == null) { + replacement = target.left; + } else { + Node successorParent = target; + Node successor = target.right; + while (successor.left != null) { + successorParent = successor; + successor = successor.left; + } + if (successorParent != target) { + successorParent.left = successor.right; + successor.right = target.right; + } + successor.left = target.left; + replacement = successor; + } + if (parent == null) return replacement; + if (parent.left == target) parent.left = replacement; + else parent.right = replacement; + return root; + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/Insert.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Insert.java new file mode 100644 index 0000000..27bcd3f --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Insert.java @@ -0,0 +1,37 @@ +package com.ankurm.interviewlab.bst; + +/** Insert with set semantics: a key that is already present changes nothing. */ +public final class Insert { + private Insert() {} + + /** Returns the root of the subtree after the insert. The caller MUST store the result. */ + public static Node recursive(Node node, int key) { + if (node == null) return new Node(key); + if (key < node.key) node.left = recursive(node.left, key); + else if (key > node.key) node.right = recursive(node.right, key); + return node; + } + + /** Same result with a loop: walk down remembering the parent, then hang the new node on it. */ + public static Node iterative(Node root, int key) { + if (root == null) return new Node(key); + Node current = root; + while (true) { + if (key == current.key) return root; + Node next = key < current.key ? current.left : current.right; + if (next == null) { + if (key < current.key) current.left = new Node(key); + else current.right = new Node(key); + return root; + } + current = next; + } + } + + /** Builds a tree by inserting the keys in the order given. */ + public static Node build(int... keys) { + Node root = null; + for (int key : keys) root = iterative(root, key); + return root; + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/Mistakes.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Mistakes.java new file mode 100644 index 0000000..a12c49b --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Mistakes.java @@ -0,0 +1,28 @@ +package com.ankurm.interviewlab.bst; + +/** Broken variants that appear in real exam answers. They exist so the tests can show the damage. */ +public final class Mistakes { + private Mistakes() {} + + /** WRONG: assigns to the parameter. Java passes the reference by value, so the caller sees nothing. */ + public static void insertLost(Node node, int key) { + if (node == null) { + node = new Node(key); + return; + } + insertLost(key < node.key ? node.left : node.right, key); + } + + /** WRONG: copies the successor key up but never removes the successor node. */ + public static Node deleteLeavesDuplicate(Node node, int key) { + if (node == null) return null; + if (key < node.key) node.left = deleteLeavesDuplicate(node.left, key); + else if (key > node.key) node.right = deleteLeavesDuplicate(node.right, key); + else { + if (node.left == null) return node.right; + if (node.right == null) return node.left; + node.key = Search.min(node.right).key; + } + return node; + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/Node.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Node.java new file mode 100644 index 0000000..49584cd --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Node.java @@ -0,0 +1,12 @@ +package com.ankurm.interviewlab.bst; + +/** One node of a binary search tree: a key and two child links. */ +public final class Node { + public int key; + public Node left; + public Node right; + + public Node(int key) { + this.key = key; + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/Problems.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Problems.java new file mode 100644 index 0000000..8b0ea1c --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Problems.java @@ -0,0 +1,120 @@ +package com.ankurm.interviewlab.bst; + +import java.util.ArrayDeque; +import java.util.HashSet; +import java.util.OptionalInt; +import java.util.Set; + +/** + * Interview problems 4 to 10. Problems 1 to 3 are {@link Validate#isBst}, {@link Queries#kthSmallest} + * and {@link Queries#lca}. + */ +public final class Problems { + private Problems() {} + + /** 4. Sum of the keys in [low, high]. Subtrees that cannot overlap the range are never entered. */ + public static long rangeSum(Node node, int low, int high) { + if (node == null) return 0; + if (node.key < low) return rangeSum(node.right, low, high); + if (node.key > high) return rangeSum(node.left, low, high); + return node.key + rangeSum(node.left, low, high) + rangeSum(node.right, low, high); + } + + /** 5. Height-balanced tree from a strictly increasing array: the middle element is the root. */ + public static Node fromSorted(int[] sorted) { + return fromSorted(sorted, 0, sorted.length - 1); + } + + private static Node fromSorted(int[] a, int lo, int hi) { + if (lo > hi) return null; + int mid = lo + (hi - lo) / 2; + Node node = new Node(a[mid]); + node.left = fromSorted(a, lo, mid - 1); + node.right = fromSorted(a, mid + 1, hi); + return node; + } + + /** 6. Inorder successor: the smallest key strictly greater than x. */ + public static OptionalInt successor(Node root, int x) { + OptionalInt best = OptionalInt.empty(); + Node current = root; + while (current != null) { + if (current.key > x) { + best = OptionalInt.of(current.key); + current = current.left; + } else { + current = current.right; + } + } + return best; + } + + /** 7. Are there two different nodes whose keys add up to target? One walk plus a HashSet. */ + public static boolean hasPairWithSum(Node root, long target) { + return pair(root, target, new HashSet<>()); + } + + private static boolean pair(Node node, long target, Set seen) { + if (node == null) return false; + if (pair(node.left, target, seen)) return true; + if (seen.contains(target - node.key)) return true; + seen.add((long) node.key); + return pair(node.right, target, seen); + } + + /** 8. Minimum difference between any two keys: only inorder neighbours can win. Needs 2+ nodes. */ + public static long minDifference(Node root) { + var stack = new ArrayDeque(); + Node current = root; + Node previous = null; + long best = Long.MAX_VALUE; + while (current != null || !stack.isEmpty()) { + while (current != null) { + stack.push(current); + current = current.left; + } + current = stack.pop(); + if (previous != null) best = Math.min(best, (long) current.key - previous.key); + previous = current; + current = current.right; + } + return best; + } + + /** 9. Exactly two keys of a BST were exchanged. Find them in the inorder walk and swap them back. */ + public static void recoverSwapped(Node root) { + var stack = new ArrayDeque(); + Node current = root; + Node previous = null; + Node first = null; + Node second = null; + while (current != null || !stack.isEmpty()) { + while (current != null) { + stack.push(current); + current = current.left; + } + current = stack.pop(); + if (previous != null && previous.key > current.key) { + if (first == null) first = previous; // the big one of the first drop + second = current; // the small one of the last drop + } + previous = current; + current = current.right; + } + if (first != null) { + int t = first.key; + first.key = second.key; + second.key = t; + } + } + + /** 10. Remove every key outside [low, high], keeping the shape of what survives. */ + public static Node trim(Node node, int low, int high) { + if (node == null) return null; + if (node.key < low) return trim(node.right, low, high); + if (node.key > high) return trim(node.left, low, high); + node.left = trim(node.left, low, high); + node.right = trim(node.right, low, high); + return node; + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/Queries.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Queries.java new file mode 100644 index 0000000..8ff3de6 --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Queries.java @@ -0,0 +1,88 @@ +package com.ankurm.interviewlab.bst; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.OptionalInt; + +/** Questions that the ordering rule answers by walking one path (or part of an inorder walk). */ +public final class Queries { + private Queries() {} + + /** k is 1-based. Iterative inorder that stops at the k-th key: O(h + k). */ + public static int kthSmallest(Node root, int k) { + if (k < 1) throw new IllegalArgumentException("k must be at least 1"); + var stack = new ArrayDeque(); + Node current = root; + while (current != null || !stack.isEmpty()) { + while (current != null) { + stack.push(current); + current = current.left; + } + current = stack.pop(); + if (--k == 0) return current.key; + current = current.right; + } + throw new NoSuchElementException("the tree has fewer than k keys"); + } + + /** Lowest common ancestor. Assumes p and q are both in the tree. */ + public static Node lca(Node root, int p, int q) { + Node current = root; + while (current != null) { + if (p < current.key && q < current.key) current = current.left; + else if (p > current.key && q > current.key) current = current.right; + else return current; + } + return null; + } + + /** Largest key less than or equal to x. */ + public static OptionalInt floor(Node root, int x) { + OptionalInt best = OptionalInt.empty(); + Node current = root; + while (current != null) { + if (current.key == x) return OptionalInt.of(x); + if (current.key < x) { + best = OptionalInt.of(current.key); // a candidate; a bigger one may be to the right + current = current.right; + } else { + current = current.left; + } + } + return best; + } + + /** Smallest key greater than or equal to x. */ + public static OptionalInt ceiling(Node root, int x) { + OptionalInt best = OptionalInt.empty(); + Node current = root; + while (current != null) { + if (current.key == x) return OptionalInt.of(x); + if (current.key > x) { + best = OptionalInt.of(current.key); // a candidate; a smaller one may be to the left + current = current.left; + } else { + current = current.right; + } + } + return best; + } + + public static List inorder(Node root) { + var out = new ArrayList(); + var stack = new ArrayDeque(); + Node current = root; + while (current != null || !stack.isEmpty()) { + while (current != null) { + stack.push(current); + current = current.left; + } + current = stack.pop(); + out.add(current.key); + current = current.right; + } + return out; + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/Search.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Search.java new file mode 100644 index 0000000..dca3560 --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Search.java @@ -0,0 +1,32 @@ +package com.ankurm.interviewlab.bst; + +/** Search, minimum and maximum. Every step discards one whole subtree. */ +public final class Search { + private Search() {} + + public static boolean recursive(Node node, int key) { + if (node == null) return false; + if (key == node.key) return true; + return recursive(key < node.key ? node.left : node.right, key); + } + + public static boolean iterative(Node root, int key) { + Node current = root; + while (current != null && current.key != key) { + current = key < current.key ? current.left : current.right; + } + return current != null; + } + + /** Smallest key: keep going left. The tree must not be empty. */ + public static Node min(Node node) { + while (node.left != null) node = node.left; + return node; + } + + /** Largest key: keep going right. The tree must not be empty. */ + public static Node max(Node node) { + while (node.right != null) node = node.right; + return node; + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/TreePrinter.java b/bst/src/main/java/com/ankurm/interviewlab/bst/TreePrinter.java new file mode 100644 index 0000000..66ece4e --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/TreePrinter.java @@ -0,0 +1,20 @@ +package com.ankurm.interviewlab.bst; + +/** Prints a tree as an indented outline: L = left child, R = right child. */ +public final class TreePrinter { + private TreePrinter() {} + + public static String outline(Node root) { + var out = new StringBuilder(); + walk(root, "", "", out); + return out.toString().stripTrailing(); + } + + private static void walk(Node node, String indent, String label, StringBuilder out) { + if (node == null) return; + out.append(indent).append(label).append(node.key).append('\n'); + String next = label.isEmpty() ? indent + " " : indent + " "; + walk(node.left, next, "L: ", out); + walk(node.right, next, "R: ", out); + } +} diff --git a/bst/src/main/java/com/ankurm/interviewlab/bst/Validate.java b/bst/src/main/java/com/ankurm/interviewlab/bst/Validate.java new file mode 100644 index 0000000..5d94558 --- /dev/null +++ b/bst/src/main/java/com/ankurm/interviewlab/bst/Validate.java @@ -0,0 +1,51 @@ +package com.ankurm.interviewlab.bst; + +/** Four ways to ask "is this a binary search tree?". Two of them are wrong on purpose. */ +public final class Validate { + private Validate() {} + + /** WRONG: compares each node only with its two direct children. */ + public static boolean childrenOnly(Node node) { + if (node == null) return true; + if (node.left != null && node.left.key >= node.key) return false; + if (node.right != null && node.right.key <= node.key) return false; + return childrenOnly(node.left) && childrenOnly(node.right); + } + + /** WRONG at the edges: int sentinels reject a legal key equal to Integer.MIN_VALUE or MAX_VALUE. */ + public static boolean intSentinels(Node node, int low, int high) { + if (node == null) return true; + if (node.key <= low || node.key >= high) return false; + return intSentinels(node.left, low, node.key) && intSentinels(node.right, node.key, high); + } + + /** Correct: every node must lie strictly between the bounds set by ALL its ancestors. */ + public static boolean isBst(Node root) { + return within(root, null, null); + } + + private static boolean within(Node node, Integer low, Integer high) { + if (node == null) return true; + if (low != null && node.key <= low) return false; + if (high != null && node.key >= high) return false; + return within(node.left, low, node.key) && within(node.right, node.key, high); + } + + /** Correct: inorder must be strictly increasing. */ + public static boolean byInorder(Node root) { + var stack = new java.util.ArrayDeque(); + Node current = root; + Integer previous = null; + while (current != null || !stack.isEmpty()) { + while (current != null) { + stack.push(current); + current = current.left; + } + current = stack.pop(); + if (previous != null && current.key <= previous) return false; + previous = current.key; + current = current.right; + } + return true; + } +} diff --git a/bst/src/test/java/com/ankurm/interviewlab/bst/CrossCheckTest.java b/bst/src/test/java/com/ankurm/interviewlab/bst/CrossCheckTest.java new file mode 100644 index 0000000..875d65d --- /dev/null +++ b/bst/src/test/java/com/ankurm/interviewlab/bst/CrossCheckTest.java @@ -0,0 +1,250 @@ +package com.ankurm.interviewlab.bst; + +import com.ankurm.interviewlab.bst.support.Transcript; +import com.ankurm.interviewlab.bst.support.Trees; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalInt; +import java.util.Random; +import java.util.TreeSet; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.*; + +/** Every operation and every problem against a brute force that does not use the ordering rule. */ +class CrossCheckTest { + private static final int ROUNDS = 2_000; + private static Transcript operations; + private static final String[] lines = new String[11]; + + @BeforeAll + static void start() { + operations = Transcript.start("15-random-operations.txt", "insert, delete, search, floor, ceiling against java.util.TreeSet (seed 42)"); + } + + @Test + void operationsAgreeWithTreeSet() { + var random = new Random(42); + Node recursive = null; + Node iterative = null; + var oracle = new TreeSet(); + int steps = 20_000; + int inserts = 0; + int deletes = 0; + for (int i = 0; i < steps; i++) { + int key = random.nextInt(200); + if (random.nextBoolean()) { + recursive = Insert.recursive(recursive, key); + iterative = Insert.iterative(iterative, key); + oracle.add(key); + inserts++; + } else { + recursive = Delete.recursive(recursive, key); + iterative = Delete.iterative(iterative, key); + oracle.remove(key); + deletes++; + } + assertEquals(new ArrayList<>(oracle), Queries.inorder(recursive)); + assertEquals(TreePrinter.outline(recursive), TreePrinter.outline(iterative)); + assertTrue(Validate.isBst(recursive)); + int probe = random.nextInt(220) - 10; + assertEquals(oracle.contains(probe), Search.recursive(recursive, probe)); + assertEquals(oracle.contains(probe), Search.iterative(iterative, probe)); + assertEquals(optional(oracle.floor(probe)), Queries.floor(recursive, probe)); + assertEquals(optional(oracle.ceiling(probe)), Queries.ceiling(recursive, probe)); + } + operations.line(steps + " random steps (" + inserts + " inserts, " + deletes + " deletes), checked after every step:"); + operations.line(" inorder equals the TreeSet, isBst is true, recursive and iterative trees have identical shape,"); + operations.line(" search, floor and ceiling give the TreeSet's answers"); + operations.flush(); + } + + private static OptionalInt optional(Integer v) { + return v == null ? OptionalInt.empty() : OptionalInt.of(v); + } + + private static void record(int number, String text) { + lines[number - 1] = String.format("%2d. %s", number, text); + } + + @AfterAll + static void write() { + var t = Transcript.start("16-ten-problems.txt", "Ten problems, each against a brute force on random trees (seeded)"); + for (int i = 0; i < 10; i++) t.line(lines[i]); + t.flush(); + } + + @Test + void p1Validate() { + var random = new Random(1); + int valid = 0; + int fooled = 0; + int total = 20_000; + for (int i = 0; i < total; i++) { + Node root = Trees.randomBinaryTree(random, random.nextInt(7), 12); + boolean truth = Trees.isBstByDefinition(root); + assertEquals(truth, Validate.isBst(root)); + assertEquals(truth, Validate.byInorder(root)); + if (truth) valid++; + if (!truth && Validate.childrenOnly(root)) fooled++; + } + assertTrue(fooled > 0); + record(1, "validate BST: " + total + " random binary trees, " + valid + " were BSTs; bounds and inorder agreed on all; childrenOnly wrongly accepted " + fooled); + } + + @Test + void p2KthSmallest() { + var random = new Random(2); + int checks = 0; + for (int i = 0; i < ROUNDS; i++) { + Node root = Trees.randomBst(random, 30, 100); + var sorted = Trees.keys(root).stream().sorted().toList(); + for (int k = 1; k <= sorted.size(); k++, checks++) assertEquals(sorted.get(k - 1), Queries.kthSmallest(root, k)); + } + record(2, "kth smallest: " + checks + " (tree, k) cases against sorting all keys"); + } + + private static List path(Node root, Node target) { + if (root == null) return null; + if (root == target) return new ArrayList<>(List.of(root)); + var p = path(root.left, target); + if (p == null) p = path(root.right, target); + if (p != null) p.addFirst(root); + return p; + } + + @Test + void p3Lca() { + var random = new Random(3); + int checks = 0; + for (int i = 0; i < ROUNDS; i++) { + Node root = Trees.randomBst(random, 20, 100); + if (root == null) continue; + var nodes = Trees.nodes(root); + for (int j = 0; j < 10; j++, checks++) { + Node p = nodes.get(random.nextInt(nodes.size())); + Node q = nodes.get(random.nextInt(nodes.size())); + var a = path(root, p); + var b = path(root, q); + Node last = null; + for (int d = 0; d < Math.min(a.size(), b.size()) && a.get(d) == b.get(d); d++) last = a.get(d); + assertSame(last, Queries.lca(root, p.key, q.key)); + } + } + record(3, "lowest common ancestor: " + checks + " pairs against comparing the two root paths"); + } + + @Test + void p4RangeSum() { + var random = new Random(4); + for (int i = 0; i < ROUNDS; i++) { + Node root = Trees.randomBst(random, 30, 100); + int low = random.nextInt(100); + int high = low + random.nextInt(50); + long brute = Trees.keys(root).stream().filter(k -> k >= low && k <= high).mapToLong(k -> k).sum(); + assertEquals(brute, Problems.rangeSum(root, low, high)); + } + assertEquals(125, Problems.rangeSum(Trees.sample(), 35, 50)); + record(4, "range sum: " + ROUNDS + " cases against filtering all keys; sample tree [35, 50] = " + Problems.rangeSum(Trees.sample(), 35, 50)); + } + + @Test + void p5FromSorted() { + for (int n = 0; n <= 500; n++) { + int[] a = IntStream.range(0, n).map(i -> i * 3).toArray(); + Node root = Problems.fromSorted(a); + assertEquals(IntStream.of(a).boxed().toList(), Queries.inorder(root)); + assertTrue(Validate.isBst(root)); + assertTrue(Balance.isBalanced(root, new Balance.Counter())); + assertEquals(32 - Integer.numberOfLeadingZeros(n), Balance.height(root)); + } + record(5, "sorted array to balanced BST: every n from 0 to 500 is a balanced BST of minimum height with the same keys"); + } + + @Test + void p6Successor() { + var random = new Random(6); + for (int i = 0; i < ROUNDS; i++) { + Node root = Trees.randomBst(random, 30, 100); + int x = random.nextInt(110) - 5; + var brute = Trees.keys(root).stream().mapToInt(k -> k).filter(k -> k > x).min(); + assertEquals(brute, Problems.successor(root, x)); + } + record(6, "inorder successor: " + ROUNDS + " cases against scanning all keys; successor(40) in the sample tree = " + Problems.successor(Trees.sample(), 40).getAsInt()); + } + + @Test + void p7PairSum() { + var random = new Random(7); + int yes = 0; + for (int i = 0; i < ROUNDS; i++) { + Node root = Trees.randomBst(random, 15, 60); + int target = random.nextInt(130); + var k = Trees.keys(root); + boolean brute = false; + for (int a = 0; a < k.size(); a++) + for (int b = a + 1; b < k.size(); b++) brute |= k.get(a) + k.get(b) == target; + assertEquals(brute, Problems.hasPairWithSum(root, target)); + if (brute) yes++; + } + record(7, "two keys summing to a target: " + ROUNDS + " cases (" + yes + " true) against all pairs"); + } + + @Test + void p8MinDifference() { + var random = new Random(8); + int checks = 0; + for (int i = 0; i < ROUNDS; i++) { + Node root = Trees.randomBst(random, 15, 1_000); + var k = Trees.keys(root); + if (k.size() < 2) continue; + long brute = Long.MAX_VALUE; + for (int a = 0; a < k.size(); a++) + for (int b = a + 1; b < k.size(); b++) brute = Math.min(brute, Math.abs((long) k.get(a) - k.get(b))); + assertEquals(brute, Problems.minDifference(root)); + checks++; + } + assertEquals(4_294_967_295L, Problems.minDifference(Insert.build(Integer.MIN_VALUE, Integer.MAX_VALUE))); + record(8, "minimum difference: " + checks + " trees against all pairs; MIN_VALUE and MAX_VALUE give 4294967295 (needs long)"); + } + + @Test + void p9Recover() { + var random = new Random(9); + int checks = 0; + for (int i = 0; i < ROUNDS; i++) { + Node root = Trees.randomBst(random, 25, 200); + var nodes = Trees.nodes(root); + if (nodes.size() < 2) continue; + var before = Queries.inorder(root); + int a = random.nextInt(nodes.size()); + int b = (a + 1 + random.nextInt(nodes.size() - 1)) % nodes.size(); + int t = nodes.get(a).key; + nodes.get(a).key = nodes.get(b).key; + nodes.get(b).key = t; + Problems.recoverSwapped(root); + assertEquals(before, Queries.inorder(root)); + checks++; + } + record(9, "recover two swapped keys: " + checks + " damaged trees, all restored"); + } + + @Test + void p10Trim() { + var random = new Random(10); + for (int i = 0; i < ROUNDS; i++) { + Node root = Trees.randomBst(random, 30, 100); + int low = random.nextInt(100); + int high = low + random.nextInt(50); + var brute = Trees.keys(root).stream().filter(k -> k >= low && k <= high).sorted().toList(); + Node trimmed = Problems.trim(root, low, high); + assertEquals(brute, Queries.inorder(trimmed)); + assertTrue(Validate.isBst(trimmed)); + } + record(10, "trim to a range: " + ROUNDS + " cases against filtering all keys, result still a BST; sample trimmed to [35, 65] = " + Queries.inorder(Problems.trim(Trees.sample(), 35, 65))); + } +} diff --git a/bst/src/test/java/com/ankurm/interviewlab/bst/DryRunTest.java b/bst/src/test/java/com/ankurm/interviewlab/bst/DryRunTest.java new file mode 100644 index 0000000..185c631 --- /dev/null +++ b/bst/src/test/java/com/ankurm/interviewlab/bst/DryRunTest.java @@ -0,0 +1,273 @@ +package com.ankurm.interviewlab.bst; + +import com.ankurm.interviewlab.bst.support.Transcript; +import com.ankurm.interviewlab.bst.support.Trees; +import org.junit.jupiter.api.Test; + +import java.util.ArrayDeque; +import java.util.List; +import java.util.OptionalInt; + +import static org.junit.jupiter.api.Assertions.*; + +/** Step-by-step transcripts. Each walk is replayed here and checked against the library result. */ +class DryRunTest { + + private static String side(int key, Node n) { + return key < n.key ? "left" : "right"; + } + + private static void walk(Transcript t, Node root, int key) { + Node current = root; + int comparisons = 0; + while (current != null) { + comparisons++; + if (current.key == key) { + t.line(" at " + current.key + ": equal, found after " + comparisons + " nodes"); + return; + } + String dir = side(key, current); + t.line(" at " + current.key + ": " + key + (key < current.key ? " < " : " > ") + current.key + ", go " + dir); + current = dir.equals("left") ? current.left : current.right; + } + t.line(" null reached after " + comparisons + " nodes: " + key + " is not in the tree"); + } + + @Test + void insert() { + var t = Transcript.start("01-insert-dry-run.txt", "Insert 50 30 70 20 40 60 80 35 65, one key at a time"); + Node recursive = null; + Node iterative = null; + for (int key : new int[] {50, 30, 70, 20, 40, 60, 80, 35, 65}) { + var path = new StringBuilder(); + Node current = iterative; + String hung = "becomes the root"; + while (current != null) { + String dir = side(key, current); + path.append(current.key).append(dir.equals("left") ? " L, " : " R, "); + hung = "new " + dir + " child of " + current.key; + current = dir.equals("left") ? current.left : current.right; + } + t.line(String.format("insert %d: %-18s -> %s", key, path.toString().replaceAll(", $", ""), hung)); + recursive = Insert.recursive(recursive, key); + iterative = Insert.iterative(iterative, key); + assertEquals(TreePrinter.outline(recursive), TreePrinter.outline(iterative)); + } + Node again = Insert.iterative(iterative, 40); + assertEquals(9, Trees.nodes(again).size()); + t.line("insert 40 again: no change (set semantics), still 9 nodes"); + t.blank().line("Tree (recursive and iterative insert give the same outline):").line(TreePrinter.outline(iterative)); + t.blank().line("inorder: " + Queries.inorder(iterative)); + assertEquals(List.of(20, 30, 35, 40, 50, 60, 65, 70, 80), Queries.inorder(iterative)); + t.flush(); + } + + @Test + void search() { + var t = Transcript.start("02-search-dry-run.txt", "Search the sample tree"); + Node root = Trees.sample(); + for (int key : new int[] {65, 45}) { + t.line("search " + key + ":"); + walk(t, root, key); + assertEquals(key == 65, Search.recursive(root, key)); + assertEquals(key == 65, Search.iterative(root, key)); + } + t.blank().line("min = " + Search.min(root).key + " (keep going left), max = " + Search.max(root).key + " (keep going right)"); + assertEquals(20, Search.min(root).key); + assertEquals(80, Search.max(root).key); + t.flush(); + } + + private static void delete(Transcript t, int key, List expected) { + Node a = Trees.sample(); + Node b = Trees.sample(); + t.line("before:").line(TreePrinter.outline(a)).blank().line("delete " + key + ":"); + walk(t, a, key); + Node target = a; + while (target.key != key) target = key < target.key ? target.left : target.right; + if (target.left != null && target.right != null) { + int s = Search.min(target.right).key; + t.line(" two children: successor = smallest key in right subtree = " + s); + t.line(" copy " + s + " into the node, then delete " + s + " from the right subtree"); + } else if (target.left != null || target.right != null) { + Node child = target.left != null ? target.left : target.right; + t.line(" one child (" + child.key + "): return that child to the parent"); + } else { + t.line(" leaf: return null to the parent"); + } + a = Delete.recursive(a, key); + b = Delete.iterative(b, key); + t.blank().line("after:").line(TreePrinter.outline(a)).blank().line("inorder: " + Queries.inorder(a)); + assertEquals(expected, Queries.inorder(a)); + assertEquals(TreePrinter.outline(a), TreePrinter.outline(b)); + assertTrue(Validate.isBst(a)); + } + + @Test + void deleteLeaf() { + var t = Transcript.start("03-delete-leaf.txt", "Delete case 1: a leaf"); + delete(t, 20, List.of(30, 35, 40, 50, 60, 65, 70, 80)); + t.flush(); + } + + @Test + void deleteOneChild() { + var t = Transcript.start("04-delete-one-child.txt", "Delete case 2: a node with one child"); + delete(t, 60, List.of(20, 30, 35, 40, 50, 65, 70, 80)); + t.flush(); + } + + @Test + void deleteTwoChildren() { + var t = Transcript.start("05-delete-two-children.txt", "Delete case 3: a node with two children (the root)"); + delete(t, 50, List.of(20, 30, 35, 40, 60, 65, 70, 80)); + t.flush(); + } + + @Test + void mistakes() { + var t = Transcript.start("06-mistakes.txt", "Two broken variants, run"); + Node root = Trees.sample(); + Mistakes.insertLost(root, 45); + t.line("insertLost(root, 45), then search 45: " + Search.iterative(root, 45)); + assertFalse(Search.iterative(root, 45)); + t.line("inorder: " + Queries.inorder(root)); + t.blank(); + Node ignored = Insert.build(50, 70); + Delete.recursive(ignored, 50); + t.line("tree 50,70: Delete.recursive(root, 50) with the result thrown away"); + t.line(" inorder from the old root variable: " + Queries.inorder(ignored)); + assertEquals(List.of(50, 70), Queries.inorder(ignored)); + Node kept = Insert.build(50, 70); + kept = Delete.recursive(kept, 50); + t.line(" root = Delete.recursive(root, 50): " + Queries.inorder(kept)); + assertEquals(List.of(70), Queries.inorder(kept)); + t.blank(); + Node dup = Mistakes.deleteLeavesDuplicate(Trees.sample(), 50); + t.line("deleteLeavesDuplicate(sample, 50)"); + t.line(" inorder: " + Queries.inorder(dup)); + t.line(" isBst: " + Validate.isBst(dup)); + assertEquals(List.of(20, 30, 35, 40, 60, 60, 65, 70, 80), Queries.inorder(dup)); + assertFalse(Validate.isBst(dup)); + t.flush(); + } + + private static boolean trace(Transcript t, Node n, Integer low, Integer high) { + if (n == null) return true; + boolean ok = (low == null || n.key > low) && (high == null || n.key < high); + t.line(String.format(" node %-3d allowed (%s, %s) %s", n.key, low == null ? "-inf" : low, + high == null ? "+inf" : high, ok ? "ok" : "VIOLATION")); + return ok && trace(t, n.left, low, n.key) && trace(t, n.right, n.key, high); + } + + @Test + void validate() { + var t = Transcript.start("07-validate.txt", "Validate BST: the children-only check, the bounds check, the sentinel trap"); + Node bad = Insert.build(50, 30, 70, 20, 40, 60, 80); + bad.left.right.key = 55; + t.line("A tree where 55 sits in the LEFT subtree of 50:").line(TreePrinter.outline(bad)).blank(); + t.line("childrenOnly: " + Validate.childrenOnly(bad)); + t.line("isBst: " + Validate.isBst(bad)); + t.line("byInorder: " + Validate.byInorder(bad) + " inorder = " + Queries.inorder(bad)); + assertTrue(Validate.childrenOnly(bad)); + assertFalse(Validate.isBst(bad)); + assertFalse(Validate.byInorder(bad)); + t.blank().line("Bounds trace (stops at the first violation):"); + assertFalse(trace(t, bad, null, null)); + t.blank(); + for (int edge : new int[] {Integer.MAX_VALUE, Integer.MIN_VALUE}) { + Node one = new Node(edge); + boolean s = Validate.intSentinels(one, Integer.MIN_VALUE, Integer.MAX_VALUE); + t.line("single node " + edge + ": intSentinels=" + s + " isBst=" + Validate.isBst(one)); + assertFalse(s); + assertTrue(Validate.isBst(one)); + } + t.flush(); + } + + @Test + void kthSmallest() { + var t = Transcript.start("08-kth-smallest.txt", "kth smallest, k = 4, on the sample tree: stack after each step"); + Node current = Trees.sample(); + var stack = new ArrayDeque(); + int k = 4; + int answer = -1; + while (answer < 0) { + while (current != null) { + stack.push(current); + t.line(String.format("push %d stack (top first) %s", current.key, keys(stack))); + current = current.left; + } + current = stack.pop(); + k--; + t.line(String.format("pop %d stack (top first) %s k left %d", current.key, keys(stack), k)); + if (k == 0) answer = current.key; + current = current.right; + } + t.blank().line("answer: " + answer); + assertEquals(40, answer); + assertEquals(40, Queries.kthSmallest(Trees.sample(), 4)); + t.flush(); + } + + private static String keys(ArrayDeque stack) { + return stack.stream().map(n -> n.key).toList().toString(); + } + + @Test + void lca() { + var t = Transcript.start("09-lca.txt", "Lowest common ancestor on the sample tree"); + Node root = Trees.sample(); + int[][] pairs = {{20, 35}, {35, 65}, {60, 65}}; + int[] expected = {30, 50, 60}; + for (int i = 0; i < pairs.length; i++) { + int p = pairs[i][0]; + int q = pairs[i][1]; + t.line("lca(" + p + ", " + q + "):"); + Node c = root; + while (true) { + if (p < c.key && q < c.key) { + t.line(" at " + c.key + ": both smaller, go left"); + c = c.left; + } else if (p > c.key && q > c.key) { + t.line(" at " + c.key + ": both larger, go right"); + c = c.right; + } else { + t.line(" at " + c.key + ": paths split here, answer " + c.key); + break; + } + } + assertEquals(expected[i], c.key); + assertEquals(expected[i], Queries.lca(root, p, q).key); + } + t.blank().line("lca(20, 99), with 99 absent, returns " + Queries.lca(root, 20, 99).key + " (a wrong-looking answer: check presence first)"); + assertEquals(50, Queries.lca(root, 20, 99).key); + t.flush(); + } + + @Test + void floorCeiling() { + var t = Transcript.start("10-floor-ceiling.txt", "floor and ceiling of 45 on the sample tree: the best candidate so far"); + Node root = Trees.sample(); + for (boolean floor : new boolean[] {true, false}) { + t.line((floor ? "floor" : "ceiling") + "(45):"); + Node c = root; + String best = "none"; + while (c != null) { + boolean candidate = floor ? c.key < 45 : c.key > 45; + if (candidate) best = String.valueOf(c.key); + String dir = c.key < 45 ? "right" : "left"; + t.line(String.format(" at %d: %s, best = %s, go %s", c.key, candidate ? "candidate" : "too " + (floor ? "big" : "small"), best, dir)); + c = dir.equals("left") ? c.left : c.right; + } + OptionalInt r = floor ? Queries.floor(root, 45) : Queries.ceiling(root, 45); + assertEquals(floor ? 40 : 50, r.getAsInt()); + assertEquals(best, String.valueOf(r.getAsInt())); + t.line(" answer " + best); + } + t.blank().line("floor(10) = " + Queries.floor(root, 10) + ", ceiling(90) = " + Queries.ceiling(root, 90)); + assertTrue(Queries.floor(root, 10).isEmpty()); + assertTrue(Queries.ceiling(root, 90).isEmpty()); + t.flush(); + } +} diff --git a/bst/src/test/java/com/ankurm/interviewlab/bst/ShapeTest.java b/bst/src/test/java/com/ankurm/interviewlab/bst/ShapeTest.java new file mode 100644 index 0000000..87eec63 --- /dev/null +++ b/bst/src/test/java/com/ankurm/interviewlab/bst/ShapeTest.java @@ -0,0 +1,150 @@ +package com.ankurm.interviewlab.bst; + +import com.ankurm.interviewlab.bst.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.TreeSet; + +import static org.junit.jupiter.api.Assertions.*; + +/** Costs counted, not timed. */ +class ShapeTest { + + private static List keys(int n) { + var list = new ArrayList(); + for (int i = 1; i <= n; i++) list.add(i); + return list; + } + + private static Node build(List keys) { + Node root = null; + for (int k : keys) root = Insert.iterative(root, k); + return root; + } + + /** Average number of nodes visited by a successful search, over every key. */ + private static double averageVisits(Node root) { + long[] sum = new long[2]; + depths(root, 1, sum); + return (double) sum[0] / sum[1]; + } + + private static void depths(Node n, int depth, long[] sum) { + if (n == null) return; + sum[0] += depth; + sum[1]++; + depths(n.left, depth + 1, sum); + depths(n.right, depth + 1, sum); + } + + @Test + void insertionOrderDecidesTheHeight() { + var t = Transcript.start("11-insertion-order.txt", "Same keys, different insertion order (n = 1023; shuffles seeded 1..5)"); + t.line(String.format("%-28s %7s %22s", "order", "height", "avg nodes per search")); + int n = 1023; + Node sorted = build(keys(n)); + row(t, "sorted 1..1023", sorted); + assertEquals(n, Balance.height(sorted)); + assertEquals(512.0, averageVisits(sorted)); + for (int seed = 1; seed <= 5; seed++) { + var k = keys(n); + Collections.shuffle(k, new Random(seed)); + Node r = build(k); + row(t, "shuffled, seed " + seed, r); + assertTrue(Balance.height(r) < 30); + } + Node balanced = Problems.fromSorted(keys(n).stream().mapToInt(Integer::intValue).toArray()); + row(t, "middle-first (fromSorted)", balanced); + assertEquals(10, Balance.height(balanced)); + t.flush(); + } + + private static void row(Transcript t, String name, Node root) { + t.line(String.format("%-28s %7d %22.2f", name, Balance.height(root), averageVisits(root))); + } + + @Test + void treeSetStaysShallowOnSortedInput() { + var t = Transcript.start("12-treeset-sorted-input.txt", "java.util.TreeSet fed sorted keys, comparisons counted by its Comparator"); + for (int n : new int[] {1_023, 100_000}) { + long[] count = {0}; + var set = new TreeSet((a, b) -> { + count[0]++; + return Integer.compare(a, b); + }); + set.addAll(keys(n)); + long worst = 0; + long total = 0; + for (int k = 1; k <= n; k++) { + count[0] = 0; + assertTrue(set.contains(k)); + worst = Math.max(worst, count[0]); + total += count[0]; + } + t.line(String.format("n = %-7d contains(): worst %d comparisons, average %.2f (plain BST on the same input: worst %d, average %.1f)", + n, worst, (double) total / n, n, (n + 1) / 2.0)); + assertTrue(worst <= 2 * (32 - Integer.numberOfLeadingZeros(n))); + } + t.flush(); + } + + @Test + void balanceCheckVisits() { + var t = Transcript.start("13-balance-visits.txt", "isBalanced: height recomputed at every node versus one postorder pass (node visits)"); + Node sample = com.ankurm.interviewlab.bst.support.Trees.sample(); + t.line("sample tree: height " + Balance.height(sample) + ", balanced " + Balance.isBalanced(sample, new Balance.Counter())); + assertEquals(4, Balance.height(sample)); + assertTrue(Balance.isBalanced(sample, new Balance.Counter())); + t.blank().line(String.format("%-26s %9s %12s %12s", "tree", "balanced", "top-down", "one pass")); + for (int n : new int[] {1_023, 16_383}) { + Node full = Problems.fromSorted(keys(n).stream().mapToInt(Integer::intValue).toArray()); + visits(t, "perfect, n = " + n, full, true); + } + // A chain fails at the root, so the early return saves the top-down version. + for (int n : new int[] {1_000, 2_000}) { + var r = visits(t, "chain, n = " + n, DeepTreeDemo.chain(n), false); + assertEquals(n - 1, r[0]); + } + // The bad case for top-down with an early return: a spine where every node passes, chains hang off it. + for (int m : new int[] {100, 200, 400}) { + Node comb = comb(m); + int n = com.ankurm.interviewlab.bst.support.Trees.nodes(comb).size(); + var r = visits(t, "comb " + m + ", n = " + n, comb, false); + assertTrue(r[0] > 20L * n); + } + t.flush(); + } + + /** Height m. Both children have height m-1: the left is another comb, the right is a plain chain. */ + private static Node comb(int m) { + if (m == 0) return null; + Node node = new Node(0); + node.left = comb(m - 1); + node.right = m == 1 ? null : DeepTreeDemo.chain(m - 1); + return node; + } + + private static long[] visits(Transcript t, String name, Node root, boolean expected) { + var a = new Balance.Counter(); + var b = new Balance.Counter(); + assertEquals(expected, Balance.isBalancedTopDown(root, a)); + assertEquals(expected, Balance.isBalanced(root, b)); + if (expected) assertTrue(a.visits > b.visits); + t.line(String.format("%-26s %9s %12d %12d", name, expected, a.visits, b.visits)); + return new long[] {a.visits, b.visits}; + } + + @Test + void deepChain() throws InterruptedException { + var t = Transcript.start("14-deep-chain.txt", "Recursion depth equals tree height"); + String report = DeepTreeDemo.run(100_000); + assertTrue(report.contains("Search.recursive: threw java.lang.StackOverflowError")); + assertTrue(report.contains("Search.iterative: returned true")); + t.line(report); + t.flush(); + } +} diff --git a/bst/src/test/java/com/ankurm/interviewlab/bst/support/Transcript.java b/bst/src/test/java/com/ankurm/interviewlab/bst/support/Transcript.java new file mode 100644 index 0000000..9b9d2e4 --- /dev/null +++ b/bst/src/test/java/com/ankurm/interviewlab/bst/support/Transcript.java @@ -0,0 +1,43 @@ +package com.ankurm.interviewlab.bst.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); + } + } +} diff --git a/bst/src/test/java/com/ankurm/interviewlab/bst/support/Trees.java b/bst/src/test/java/com/ankurm/interviewlab/bst/support/Trees.java new file mode 100644 index 0000000..b0bde9e --- /dev/null +++ b/bst/src/test/java/com/ankurm/interviewlab/bst/support/Trees.java @@ -0,0 +1,62 @@ +package com.ankurm.interviewlab.bst.support; + +import com.ankurm.interviewlab.bst.Insert; +import com.ankurm.interviewlab.bst.Node; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/** Sample and random trees, plus brute-force helpers that ignore the ordering rule on purpose. */ +public final class Trees { + private Trees() {} + + /** The tree used in the article's diagrams. */ + public static Node sample() { + return Insert.build(50, 30, 70, 20, 40, 60, 80, 35, 65); + } + + public static Node randomBst(Random random, int maxNodes, int keyBound) { + Node root = null; + for (int i = random.nextInt(maxNodes + 1); i > 0; i--) { + root = Insert.iterative(root, random.nextInt(keyBound)); + } + return root; + } + + /** Any shape, any keys: usually NOT a search tree. */ + public static Node randomBinaryTree(Random random, int nodes, int keyBound) { + if (nodes == 0) return null; + Node node = new Node(random.nextInt(keyBound)); + int left = random.nextInt(nodes); + node.left = randomBinaryTree(random, left, keyBound); + node.right = randomBinaryTree(random, nodes - 1 - left, keyBound); + return node; + } + + public static List nodes(Node root) { + var out = new ArrayList(); + collect(root, out); + return out; + } + + private static void collect(Node node, List out) { + if (node == null) return; + collect(node.left, out); + out.add(node); + collect(node.right, out); + } + + public static List keys(Node root) { + return nodes(root).stream().map(n -> n.key).toList(); + } + + /** The definition, checked literally: every key on the left is smaller, every key on the right larger. */ + public static boolean isBstByDefinition(Node root) { + for (Node n : nodes(root)) { + if (keys(n.left).stream().anyMatch(k -> k >= n.key)) return false; + if (keys(n.right).stream().anyMatch(k -> k <= n.key)) return false; + } + return true; + } +}