Add binary-search module: iterative/recursive search, overflow-safe midpoint, lowerBound/upperBound, rotated arrays, search on the answer, 10 interview problems (14 tests, 14 transcripts)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b3tGdV3Vm51QUZxg2x
This commit is contained in:
@@ -30,6 +30,7 @@ One module per article. This repository currently holds:
|
||||
| [`elevator`](elevator/) | Low-Level Design: Elevator System in Java (State Pattern and Scheduling) | this commit |
|
||||
| [`experienced-2-3y`](experienced-2-3y/) | Java Interview Questions for 2 to 3 Years Experience (Scenario-Based, with Answers) | this commit |
|
||||
| [`food-delivery`](food-delivery/) | Low-Level Design: Food Delivery App (Zomato/Swiggy-Style) in Java | this commit |
|
||||
| [`binary-search`](binary-search/) | Binary Search in Java: Iterative, Recursive, Lower/Upper Bound and 10 Interview Problems | this commit |
|
||||
|
||||
## `collections` module
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# binary-search
|
||||
|
||||
Companion code for the ankurm.com article **Binary Search in Java: Iterative, Recursive, Lower/Upper Bound and 10 Interview Problems**
|
||||
(a full rewrite of the 2015 post "Implementing Binary Search in Java", same URL).
|
||||
|
||||
Iterative and recursive search, the overflow-safe midpoint, `lowerBound`/`upperBound`, rotated arrays, "search on the answer" and ten
|
||||
interview problems, each cross-checked against an obviously-correct brute-force version on seeded random inputs. Every figure and console
|
||||
line in the article is quoted from a file in `output/`, which the JUnit tests write while asserting the same numbers. 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.x | `mvn -version` |
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
cd binary-search
|
||||
export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
|
||||
./scripts/run-all.sh # runs 14 tests and regenerates output/*.txt
|
||||
java src/main/java/com/ankurm/interviewlab/binarysearch/InteractiveDemo.java # the original console program
|
||||
```
|
||||
|
||||
The first Maven run must be online so the plugins land in the local cache.
|
||||
|
||||
## Source layout
|
||||
|
||||
```
|
||||
binary-search/
|
||||
├── pom.xml
|
||||
├── scripts/run-all.sh
|
||||
├── src/main/java/com/ankurm/interviewlab/binarysearch/
|
||||
│ ├── BinarySearch.java iterative, recursive, lowerBound, upperBound, first/last/count
|
||||
│ ├── Overflow.java the (lo + hi) / 2 bug at 2,000,000,000 elements, and two fixes
|
||||
│ ├── RotatedArray.java search, minimum, and the minimum with duplicates
|
||||
│ ├── SearchOnAnswer.java firstTrue template, integer sqrt, Koko bananas, ship packages
|
||||
│ ├── InterviewProblems.java range, peak element, 2D matrix; index of all ten problems
|
||||
│ ├── BruteForce.java slow, obviously-correct references (no shared helpers)
|
||||
│ ├── DryRuns.java instrumented copies that record every step
|
||||
│ ├── Pitfalls.java two plausible-looking wrong versions
|
||||
│ └── InteractiveDemo.java the original 2015 console program
|
||||
├── src/test/java/.../ one test class per output file group
|
||||
└── output/*.txt captured real output
|
||||
```
|
||||
|
||||
## Captured output (`output/`)
|
||||
|
||||
| File | What it shows |
|
||||
|---|---|
|
||||
| `01-dry-run-iterative.txt` | the three searches from the original article, step by step |
|
||||
| `02-recursive-vs-iterative.txt` | identical answers on 2,003 keys; recursion depth 5 / 11 / 21 |
|
||||
| `03-overflow-mid.txt` | `(lo + hi) / 2` wrapping negative and throwing at n = 2,000,000,000 |
|
||||
| `04-lower-upper-bound.txt` | bounds, first/last/count and `Arrays.binarySearch` on duplicates |
|
||||
| `05-rotated-array.txt` | rotated search and minimum traces; the duplicates degradation |
|
||||
| `06-search-on-answer.txt` | how many yes/no questions sqrt, Koko and ship packages ask |
|
||||
| `07-ten-problems.txt` | one example per problem beside the brute-force answer |
|
||||
| `08-random-agreement.txt` | 34,000 seeded comparisons, 0 disagreements |
|
||||
| `09-operation-counts.txt` | elements looked at: linear vs binary, n = 10 to 1,000,000,000 |
|
||||
| `10-pitfalls.txt` | the classic mistakes, each reproduced |
|
||||
| `11-interactive-session.txt` | the original program, same sample session as the 2015 post |
|
||||
| `12-jdk-source.txt` | the JDK's own midpoint line, read from `lib/src.zip` |
|
||||
| `13-sixteen-elements.txt` | 26 among 16 values: four probes, against 13 for a linear scan |
|
||||
| `14-no-bound-methods.txt` | reflection check: no lowerBound/upperBound in Arrays, Collections or List |
|
||||
@@ -0,0 +1,20 @@
|
||||
Iterative binary search, traced step by step on [10, 20, 30, 40, 45]
|
||||
====================================================================
|
||||
|
||||
search for 40
|
||||
low=0 high=4 mid=2 a[mid]=30 -> 40 > 30, low=3
|
||||
low=3 high=4 mid=3 a[mid]=40 -> equals 40, return 3
|
||||
result: 3 (position 4 counting from 1), 2 elements compared
|
||||
|
||||
search for 10
|
||||
low=0 high=4 mid=2 a[mid]=30 -> 10 < 30, high=1
|
||||
low=0 high=1 mid=0 a[mid]=10 -> equals 10, return 0
|
||||
result: 0 (position 1 counting from 1), 2 elements compared
|
||||
|
||||
search for 25
|
||||
low=0 high=4 mid=2 a[mid]=30 -> 25 < 30, high=1
|
||||
low=0 high=1 mid=0 a[mid]=10 -> 25 > 10, low=1
|
||||
low=1 high=1 mid=1 a[mid]=20 -> 25 > 20, low=2
|
||||
low=2 high=1 -> low > high, return -1
|
||||
result: -1, 3 elements compared
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
Recursive vs iterative: same answers, and how deep the recursion goes
|
||||
=====================================================================
|
||||
|
||||
n=1000, elements 0,2,4,...,1998: 2003 keys from -1 to 2001 (present and absent)
|
||||
give identical answers from the iterative and the recursive version.
|
||||
|
||||
n= 10 absent key above the last element: result=-1, recursion frames=5 (iterative uses 0 extra frames)
|
||||
n= 1,000 absent key above the last element: result=-1, recursion frames=11 (iterative uses 0 extra frames)
|
||||
n=1,000,000 absent key above the last element: result=-1, recursion frames=21 (iterative uses 0 extra frames)
|
||||
@@ -0,0 +1,21 @@
|
||||
The (lo + hi) / 2 bug on a sorted sequence of 2,000,000,000 elements (no array: see Overflow.Sequence)
|
||||
====================================================================================================
|
||||
|
||||
Plain int arithmetic, lo=1000000000 hi=1999999999:
|
||||
lo + hi = -1294967297
|
||||
(lo + hi) / 2 = -647483648
|
||||
lo + (hi - lo) / 2 = 1499999999
|
||||
(lo + hi) >>> 1 = 1499999999
|
||||
|
||||
Broken (lo + hi) / 2, searching for the last element, 1999999999:
|
||||
lo=0 hi=1999999999 lo+hi=1999999999 mid=999999999
|
||||
lo=1000000000 hi=1999999999 lo+hi=-1294967297 mid=-647483648
|
||||
-> java.lang.ArrayIndexOutOfBoundsException: Index -647483648 out of bounds for length 2000000000
|
||||
|
||||
Fixed with lo + (hi - lo) / 2: found index 1999999999 after 31 steps. First and last steps:
|
||||
lo=0 hi=1999999999 hi-lo=1999999999 mid=999999999
|
||||
lo=1000000000 hi=1999999999 hi-lo=999999999 mid=1499999999
|
||||
...
|
||||
lo=1999999999 hi=1999999999 hi-lo=0 mid=1999999999
|
||||
|
||||
Fixed with (lo + hi) >>> 1: found index 1999999999
|
||||
@@ -0,0 +1,27 @@
|
||||
lowerBound / upperBound on [1, 2, 2, 2, 2, 2, 3, 5, 5, 8] (indexes 0..9)
|
||||
========================================================================
|
||||
|
||||
key | lowerBound | upperBound | first | last | count | iterative | Arrays.binarySearch
|
||||
0 | 0 | 0 | -1 | -1 | 0 | -1 | -1
|
||||
1 | 0 | 1 | 0 | 0 | 1 | 0 | 0
|
||||
2 | 1 | 6 | 1 | 5 | 5 | 4 | 4
|
||||
3 | 6 | 7 | 6 | 6 | 1 | 6 | 6
|
||||
4 | 7 | 7 | -1 | -1 | 0 | -1 | -8
|
||||
5 | 7 | 9 | 7 | 8 | 2 | 7 | 7
|
||||
8 | 9 | 10 | 9 | 9 | 1 | 9 | 9
|
||||
9 | 10 | 10 | -1 | -1 | 0 | -1 | -11
|
||||
|
||||
lowerBound for 2:
|
||||
low=0 high=10 mid=5 a[mid]=2 -> 2 >= 2, mid might be the answer, high=5
|
||||
low=0 high=5 mid=2 a[mid]=2 -> 2 >= 2, mid might be the answer, high=2
|
||||
low=0 high=2 mid=1 a[mid]=2 -> 2 >= 2, mid might be the answer, high=1
|
||||
low=0 high=1 mid=0 a[mid]=1 -> 1 < 2, everything up to mid is too small, low=1
|
||||
low=1 high=1 -> range is empty, answer 1
|
||||
|
||||
lowerBound for 4:
|
||||
low=0 high=10 mid=5 a[mid]=2 -> 2 < 4, everything up to mid is too small, low=6
|
||||
low=6 high=10 mid=8 a[mid]=5 -> 5 >= 4, mid might be the answer, high=8
|
||||
low=6 high=8 mid=7 a[mid]=5 -> 5 >= 4, mid might be the answer, high=7
|
||||
low=6 high=7 mid=6 a[mid]=3 -> 3 < 4, everything up to mid is too small, low=7
|
||||
low=7 high=7 -> range is empty, answer 7
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
Rotated sorted array [4, 5, 6, 7, 0, 1, 2]
|
||||
==========================================
|
||||
|
||||
search for 0
|
||||
low=0 high=6 mid=3 a[mid]=7 | left half 4..7 is sorted and does not hold 0 -> low=4
|
||||
low=4 high=6 mid=5 a[mid]=1 | left half 0..1 is sorted and holds 0 -> high=4
|
||||
low=4 high=4 mid=4 a[mid]=0 -> found at 4
|
||||
|
||||
search for 3
|
||||
low=0 high=6 mid=3 a[mid]=7 | left half 4..7 is sorted and does not hold 3 -> low=4
|
||||
low=4 high=6 mid=5 a[mid]=1 | left half 0..1 is sorted and does not hold 3 -> low=6
|
||||
low=6 high=6 mid=6 a[mid]=2 | left half 2..2 is sorted and does not hold 3 -> low=7
|
||||
low=7 high=6 -> low > high, return -1
|
||||
|
||||
find the minimum (the rotation point)
|
||||
low=0 high=6 mid=3 a[mid]=7 a[high]=2 -> 7 > 2, the drop is right of mid, low=4
|
||||
low=4 high=6 mid=5 a[mid]=1 a[high]=2 -> 1 <= 2, the drop is at mid or left of it, high=5
|
||||
low=4 high=5 mid=4 a[mid]=0 a[high]=1 -> 0 <= 1, the drop is at mid or left of it, high=4
|
||||
low=4 high=4 -> minimum 0 at index 4
|
||||
|
||||
exhaustive check, every rotation of every distinct array of length 1..12, every key: 2184 searches, 0 disagreements
|
||||
|
||||
With duplicates the same idea can degrade to a linear scan (iterations of the find-minimum loop):
|
||||
n= 16 minimum at index 1: distinct values 4 iterations many duplicates 14 iterations
|
||||
n= 256 minimum at index 1: distinct values 8 iterations many duplicates 254 iterations
|
||||
n= 4096 minimum at index 1: distinct values 12 iterations many duplicates 4094 iterations
|
||||
@@ -0,0 +1,20 @@
|
||||
Binary search on the answer: how many times the yes/no question was asked
|
||||
=========================================================================
|
||||
|
||||
Integer square root = largest m with m*m <= x; the question is "is m*m > x?"
|
||||
sqrt(8) = 2 asked 3 times, instead of trying up to 9 candidates
|
||||
sqrt(16) = 4 asked 4 times, instead of trying up to 17 candidates
|
||||
sqrt(1,000,000,007) = 31622 asked 30 times, instead of trying up to 1,000,000,008 candidates
|
||||
sqrt(2,147,483,647) = 46340 asked 31 times, instead of trying up to 2,147,483,648 candidates
|
||||
|
||||
Koko eating bananas: smallest speed k with sum(ceil(pile / k)) <= h
|
||||
piles=[3, 6, 7, 11] h=8 -> speed 4 asked 4 times (candidates 1..11)
|
||||
piles=[30, 11, 23, 4, 20] h=5 -> speed 30 asked 4 times (candidates 1..30)
|
||||
piles=[30, 11, 23, 4, 20] h=6 -> speed 23 asked 5 times (candidates 1..30)
|
||||
for [3, 6, 7, 11], hours needed at speed 1..11: 27, 15, 10, 8, 8, 6, 5, 5, 5, 5, 4
|
||||
is that <= 8? F F F T T T T T T T T
|
||||
piles=[1000000000, 999999999, 500000000] h=10 -> speed 250,000,000 asked 29 times (candidates 1..1,000,000,000); checked: speed-1 needs 13 hours
|
||||
|
||||
Ship packages within D days: smallest capacity so that, loading in order, D days are enough
|
||||
weights=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] days=5 -> capacity 15 asked 5 times (candidates 10..55)
|
||||
days needed at capacity 15: 5; at capacity 14: 6
|
||||
@@ -0,0 +1,20 @@
|
||||
Ten interview problems: fast answer beside the brute-force answer
|
||||
=================================================================
|
||||
|
||||
1. search insert position [1, 3, 5, 6] key=5 fast=2 brute-force=2
|
||||
1. search insert position [1, 3, 5, 6] key=2 fast=1 brute-force=1
|
||||
1. search insert position [1, 3, 5, 6] key=7 fast=4 brute-force=4
|
||||
1. search insert position [1, 3, 5, 6] key=0 fast=0 brute-force=0
|
||||
2. first and last position [5, 7, 7, 8, 8, 10] key=8 fast=[3, 4] brute-force=[3, 4]
|
||||
2. first and last position [5, 7, 7, 8, 8, 10] key=6 fast=[-1, -1] brute-force=[-1, -1]
|
||||
3. count occurrences [1, 2, 2, 2, 2, 2, 3] key=2 fast=5 brute-force=5
|
||||
4. search in rotated array [4, 5, 6, 7, 0, 1, 2] key=0 fast=4 brute-force=4
|
||||
4. search in rotated array [4, 5, 6, 7, 0, 1, 2] key=3 fast=-1 brute-force=-1
|
||||
5. minimum of rotated array [3, 4, 5, 1, 2] (index of min) fast=3 brute-force=3
|
||||
6. find a peak element [1, 2, 1, 3, 5, 6, 4] (any peak is valid) fast=5 brute-force=peaks at 1 and 5, 5 is a peak: true
|
||||
7. integer square root x=4 fast=2 brute-force=2
|
||||
7. integer square root x=8 fast=2 brute-force=2
|
||||
8. koko eating bananas [3, 6, 7, 11] h=8 fast=4 brute-force=4
|
||||
9. ship packages within D days weights 1..10 days=5 fast=15 brute-force=15
|
||||
10. search a 2D matrix 3x4 matrix target=3 fast=true brute-force=true
|
||||
10. search a 2D matrix 3x4 matrix target=13 fast=false brute-force=false
|
||||
@@ -0,0 +1,13 @@
|
||||
Seeded random cross-check (Random(2026)): fast solution vs brute force
|
||||
======================================================================
|
||||
|
||||
plain search + insert position (1) 3,000 cases 0 disagreements
|
||||
first and last position (2) 3,000 cases 0 disagreements
|
||||
count occurrences (3) 3,000 cases 0 disagreements
|
||||
search in rotated array (4) 3,000 cases 0 disagreements
|
||||
minimum of rotated array, distinct + duplicates (5) 6,000 cases 0 disagreements
|
||||
find a peak element (6) 3,000 cases 0 disagreements
|
||||
integer square root, small + near Integer.MAX_VALUE (7) 4,000 cases 0 disagreements
|
||||
koko eating bananas (8) 3,000 cases 0 disagreements
|
||||
ship packages within D days (9) 3,000 cases 0 disagreements
|
||||
search a 2D matrix (10) 3,000 cases 0 disagreements
|
||||
@@ -0,0 +1,11 @@
|
||||
Elements looked at: linear scan vs binary search (counted, not timed)
|
||||
=====================================================================
|
||||
|
||||
n | linear scan, absent key | binary, worst over every key | floor(log2 n) + 1
|
||||
10 | 10 | 4 | 4
|
||||
1,000 | 1,000 | 10 | 10
|
||||
100,000 | 100,000 | 17 | 17
|
||||
1,000,000 | 1,000,000 | 20 | 20
|
||||
|
||||
n=1,000,000,000 (memory-free Sequence): the most probes seen over 10,002 sampled keys = 30; floor(log2 n) + 1 = 30
|
||||
a linear scan of the same data would look at up to 1,000,000,000 elements
|
||||
@@ -0,0 +1,28 @@
|
||||
Six classic binary-search mistakes, each reproduced
|
||||
===================================================
|
||||
|
||||
1. hi = a.length with lo <= hi, searching [1, 3, 5] for 9
|
||||
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
|
||||
correct version returns -1
|
||||
|
||||
2. lo = mid instead of lo = mid + 1, searching [1, 2] for 2 (stopped after 6 iterations)
|
||||
iteration 1: low=0 high=1 mid=0 a[mid]=1
|
||||
iteration 2: low=0 high=1 mid=0 a[mid]=1
|
||||
iteration 3: low=0 high=1 mid=0 a[mid]=1
|
||||
iteration 4: low=0 high=1 mid=0 a[mid]=1
|
||||
iteration 5: low=0 high=1 mid=0 a[mid]=1
|
||||
iteration 6: low=0 high=1 mid=0 a[mid]=1
|
||||
correct version returns 1
|
||||
|
||||
3. unsorted input [5, 1, 2, 9, 3], key 3
|
||||
binary search returns -1, a linear scan returns 4
|
||||
|
||||
4. duplicates [1, 2, 2, 2, 2, 2, 3], key 2 occurs at indexes 1..5
|
||||
iterative returns 3, Arrays.binarySearch returns 3, firstOccurrence returns 1, lastOccurrence returns 5
|
||||
|
||||
5. Arrays.binarySearch does not return -1 for "not found": it returns -(insertion point) - 1
|
||||
Arrays.binarySearch([10, 20, 30, 40, 45], 25) = -3 (== -1? false) insertion point = 2
|
||||
Arrays.binarySearch([10, 20, 30, 40, 45], 5) = -1 (== -1? true) insertion point = 0
|
||||
Arrays.binarySearch([10, 20, 30, 40, 45], 50) = -6 (== -1? false) insertion point = 5
|
||||
|
||||
6. overflow of (lo + hi) / 2: see 03-overflow-mid.txt
|
||||
@@ -0,0 +1,19 @@
|
||||
InteractiveDemo (the original console program) with scripted input; values echoed like a terminal
|
||||
=================================================================================================
|
||||
|
||||
Enter how many numbers to be stored: 5
|
||||
Enter 5 numbers in INCREASING ORDER:
|
||||
Element [1]: 10
|
||||
Element [2]: 20
|
||||
Element [3]: 30
|
||||
Element [4]: 40
|
||||
Element [5]: 45
|
||||
Enter the number to search: 40
|
||||
Number 40 found at position 4
|
||||
Want to search another number? (y/n): y
|
||||
Enter the number to search: 10
|
||||
Number 10 found at position 1
|
||||
Want to search another number? (y/n): y
|
||||
Enter the number to search: 25
|
||||
Number NOT found in the array.
|
||||
Want to search another number? (y/n): n
|
||||
@@ -0,0 +1,27 @@
|
||||
How the JDK itself computes the midpoint (read from this JDK's lib/src.zip)
|
||||
===========================================================================
|
||||
|
||||
JDK: 25.0.5.1+2-LTS
|
||||
|
||||
java/util/Arrays.java, binarySearch0(int[] ...), lines 1698 onwards:
|
||||
1698 private static int binarySearch0(int[] a, int fromIndex, int toIndex,
|
||||
1699 int key) {
|
||||
1700 int low = fromIndex;
|
||||
1701 int high = toIndex - 1;
|
||||
1702
|
||||
1703 while (low <= high) {
|
||||
1704 int mid = (low + high) >>> 1;
|
||||
1705 int midVal = a[mid];
|
||||
1706
|
||||
1707 if (midVal < key)
|
||||
1708 low = mid + 1;
|
||||
1709 else if (midVal > key)
|
||||
1710 high = mid - 1;
|
||||
1711 else
|
||||
1712 return mid; // key found
|
||||
1713 }
|
||||
1714 return -(low + 1); // key not found.
|
||||
1715 }
|
||||
|
||||
java/util/Collections.java, indexedBinarySearch(...):
|
||||
333 int mid = (low + high) >>> 1;
|
||||
@@ -0,0 +1,8 @@
|
||||
Searching for 26 among 2, 4, 6, ... 32 (sixteen values, indexes 0..15)
|
||||
======================================================================
|
||||
|
||||
low=0 high=15 mid=7 a[mid]=16 -> 26 > 16, low=8
|
||||
low=8 high=15 mid=11 a[mid]=24 -> 26 > 24, low=12
|
||||
low=12 high=15 mid=13 a[mid]=28 -> 26 < 28, high=12
|
||||
low=12 high=12 mid=12 a[mid]=26 -> equals 26, return 12
|
||||
result: index 12 after 4 elements compared; a linear scan needs 13
|
||||
@@ -0,0 +1,8 @@
|
||||
Public methods with "bound" or "binarySearch" in their name on java.util.Arrays, Collections and List
|
||||
====================================================================================================
|
||||
|
||||
JDK: 25.0.5.1+2-LTS
|
||||
|
||||
java.util.Arrays methods named *bound*: [] binarySearch overloads: 18
|
||||
java.util.Collections methods named *bound*: [] binarySearch overloads: 2
|
||||
java.util.List methods named *bound*: [] binarySearch overloads: 0
|
||||
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.ankurm.interviewlab</groupId>
|
||||
<artifactId>binary-search</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>java-interview-lab :: binary-search</name>
|
||||
<description>
|
||||
Runnable companion code for ankurm.com's "Binary Search in Java" article: iterative, recursive, lower/upper bound, rotated arrays, search on the answer and 10 interview problems, each cross-checked against brute force.
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<junit.version>6.1.3</junit.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-launcher</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.14.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<argLine>-Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+9
@@ -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
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
/**
|
||||
* The core of the article: plain search (iterative and recursive) and the two "boundary" searches
|
||||
* that every harder problem is built from.
|
||||
*
|
||||
* <p>All methods expect an array sorted in ascending order. None of them checks that: with unsorted
|
||||
* input they return garbage silently (see {@link Pitfalls}).
|
||||
*/
|
||||
public final class BinarySearch {
|
||||
private BinarySearch() {}
|
||||
|
||||
/** Index of {@code key}, or -1. The loop invariant: if the key exists, it is inside [lo, hi]. */
|
||||
public static int iterative(int[] a, int key) {
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2; // never (lo + hi) / 2, see Overflow
|
||||
if (a[mid] == key) {
|
||||
return mid;
|
||||
}
|
||||
if (key > a[mid]) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Same algorithm, with the loop replaced by a call: each call owns the range [lo, hi]. */
|
||||
public static int recursive(int[] a, int key) {
|
||||
return recursive(a, key, 0, a.length - 1);
|
||||
}
|
||||
|
||||
static int recursive(int[] a, int key, int lo, int hi) {
|
||||
if (lo > hi) {
|
||||
return -1;
|
||||
}
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] == key) {
|
||||
return mid;
|
||||
}
|
||||
return key > a[mid] ? recursive(a, key, mid + 1, hi) : recursive(a, key, lo, mid - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* First index whose element is {@code >= key}; {@code a.length} if there is none. Works on the
|
||||
* half-open range [lo, hi), so {@code hi = a.length} is a legal answer, not an out-of-bounds read.
|
||||
*/
|
||||
public static int lowerBound(int[] a, int key) {
|
||||
int lo = 0;
|
||||
int hi = a.length;
|
||||
while (lo < hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] < key) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/** First index whose element is {@code > key}; {@code a.length} if there is none. */
|
||||
public static int upperBound(int[] a, int key) {
|
||||
int lo = 0;
|
||||
int hi = a.length;
|
||||
while (lo < hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] <= key) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/** Leftmost index of {@code key}, or -1. */
|
||||
public static int firstOccurrence(int[] a, int key) {
|
||||
int i = lowerBound(a, key);
|
||||
return i < a.length && a[i] == key ? i : -1;
|
||||
}
|
||||
|
||||
/** Rightmost index of {@code key}, or -1. */
|
||||
public static int lastOccurrence(int[] a, int key) {
|
||||
int i = upperBound(a, key) - 1;
|
||||
return i >= 0 && a[i] == key ? i : -1;
|
||||
}
|
||||
|
||||
/** How many times {@code key} occurs: two searches, no loop over the matches. */
|
||||
public static int count(int[] a, int key) {
|
||||
return upperBound(a, key) - lowerBound(a, key);
|
||||
}
|
||||
|
||||
/** Where {@code key} would have to be inserted to keep the array sorted (leftmost such slot). */
|
||||
public static int insertPosition(int[] a, int key) {
|
||||
return lowerBound(a, key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
/** Slow, obviously-correct references. Written independently of the fast versions; no shared helpers. */
|
||||
public final class BruteForce {
|
||||
private BruteForce() {}
|
||||
|
||||
public static int indexOf(int[] a, int key) {
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
if (a[i] == key) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int searchInsert(int[] a, int key) {
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
if (a[i] >= key) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return a.length;
|
||||
}
|
||||
|
||||
public static int[] searchRange(int[] a, int key) {
|
||||
int first = -1;
|
||||
int last = -1;
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
if (a[i] == key) {
|
||||
if (first < 0) {
|
||||
first = i;
|
||||
}
|
||||
last = i;
|
||||
}
|
||||
}
|
||||
return new int[] {first, last};
|
||||
}
|
||||
|
||||
public static int count(int[] a, int key) {
|
||||
int c = 0;
|
||||
for (int v : a) {
|
||||
if (v == key) {
|
||||
c++;
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
public static int minIndex(int[] a) {
|
||||
int best = 0;
|
||||
for (int i = 1; i < a.length; i++) {
|
||||
if (a[i] < a[best]) {
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public static boolean isPeak(int[] a, int i) {
|
||||
long left = i == 0 ? Long.MIN_VALUE : a[i - 1];
|
||||
long right = i == a.length - 1 ? Long.MIN_VALUE : a[i + 1];
|
||||
return a[i] > left && a[i] > right;
|
||||
}
|
||||
|
||||
public static int sqrt(int x) {
|
||||
long m = 0;
|
||||
while ((m + 1) * (m + 1) <= x) {
|
||||
m++;
|
||||
}
|
||||
return (int) m;
|
||||
}
|
||||
|
||||
/** Try every speed from 1 upwards; count hours by literally eating each pile down. */
|
||||
public static int minEatingSpeed(int[] piles, int h) {
|
||||
for (int speed = 1; ; speed++) {
|
||||
int hours = 0;
|
||||
for (int p : piles) {
|
||||
int left = p;
|
||||
while (left > 0) {
|
||||
left -= speed;
|
||||
hours++;
|
||||
}
|
||||
}
|
||||
if (hours <= h) {
|
||||
return speed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Try every capacity from the heaviest package upwards; load the ship day by day. */
|
||||
public static int shipWithinDays(int[] weights, int days) {
|
||||
int heaviest = 0;
|
||||
for (int w : weights) {
|
||||
heaviest = Math.max(heaviest, w);
|
||||
}
|
||||
for (int capacity = heaviest; ; capacity++) {
|
||||
int day = 1;
|
||||
int onShip = 0;
|
||||
for (int w : weights) {
|
||||
if (onShip + w <= capacity) {
|
||||
onShip += w;
|
||||
} else {
|
||||
day++;
|
||||
onShip = w;
|
||||
}
|
||||
}
|
||||
if (day <= days) {
|
||||
return capacity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean searchMatrix(int[][] m, int target) {
|
||||
for (int[] row : m) {
|
||||
for (int v : row) {
|
||||
if (v == target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Instrumented copies of the real algorithms. Each one makes exactly the same moves as its original and
|
||||
* writes down what it saw at every step; the tests assert that the result equals the original's result,
|
||||
* so a trace can never drift from the code it explains.
|
||||
*/
|
||||
public final class DryRuns {
|
||||
private DryRuns() {}
|
||||
|
||||
/** Result, the human-readable steps, and how many elements were compared ("probes"). */
|
||||
public record Run(int result, List<String> lines, int probes) {}
|
||||
|
||||
public static Run iterative(int[] a, int key) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
int probes = 0;
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
probes++;
|
||||
String head = "low=" + lo + " high=" + hi + " mid=" + mid + " a[mid]=" + a[mid];
|
||||
if (a[mid] == key) {
|
||||
lines.add(head + " -> equals " + key + ", return " + mid);
|
||||
return new Run(mid, lines, probes);
|
||||
}
|
||||
if (key > a[mid]) {
|
||||
lines.add(head + " -> " + key + " > " + a[mid] + ", low=" + (mid + 1));
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
lines.add(head + " -> " + key + " < " + a[mid] + ", high=" + (mid - 1));
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
lines.add("low=" + lo + " high=" + hi + " -> low > high, return -1");
|
||||
return new Run(-1, lines, probes);
|
||||
}
|
||||
|
||||
/** Trace of {@link BinarySearch#lowerBound}: note the half-open range, high starts at a.length. */
|
||||
public static Run lowerBound(int[] a, int key) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
int lo = 0;
|
||||
int hi = a.length;
|
||||
int probes = 0;
|
||||
while (lo < hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
probes++;
|
||||
String head = "low=" + lo + " high=" + hi + " mid=" + mid + " a[mid]=" + a[mid];
|
||||
if (a[mid] < key) {
|
||||
lines.add(head + " -> " + a[mid] + " < " + key + ", everything up to mid is too small, low=" + (mid + 1));
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
lines.add(head + " -> " + a[mid] + " >= " + key + ", mid might be the answer, high=" + mid);
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
lines.add("low=" + lo + " high=" + hi + " -> range is empty, answer " + lo);
|
||||
return new Run(lo, lines, probes);
|
||||
}
|
||||
|
||||
public static Run rotatedSearch(int[] a, int key) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
int probes = 0;
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
probes++;
|
||||
String head = "low=" + lo + " high=" + hi + " mid=" + mid + " a[mid]=" + a[mid];
|
||||
if (a[mid] == key) {
|
||||
lines.add(head + " -> found at " + mid);
|
||||
return new Run(mid, lines, probes);
|
||||
}
|
||||
if (a[lo] <= a[mid]) {
|
||||
String half = "left half " + a[lo] + ".." + a[mid] + " is sorted";
|
||||
if (a[lo] <= key && key < a[mid]) {
|
||||
lines.add(head + " | " + half + " and holds " + key + " -> high=" + (mid - 1));
|
||||
hi = mid - 1;
|
||||
} else {
|
||||
lines.add(head + " | " + half + " and does not hold " + key + " -> low=" + (mid + 1));
|
||||
lo = mid + 1;
|
||||
}
|
||||
} else {
|
||||
String half = "right half " + a[mid] + ".." + a[hi] + " is sorted";
|
||||
if (a[mid] < key && key <= a[hi]) {
|
||||
lines.add(head + " | " + half + " and holds " + key + " -> low=" + (mid + 1));
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
lines.add(head + " | " + half + " and does not hold " + key + " -> high=" + (mid - 1));
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.add("low=" + lo + " high=" + hi + " -> low > high, return -1");
|
||||
return new Run(-1, lines, probes);
|
||||
}
|
||||
|
||||
public static Run rotatedMin(int[] a) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
int probes = 0;
|
||||
while (lo < hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
probes++;
|
||||
String head = "low=" + lo + " high=" + hi + " mid=" + mid + " a[mid]=" + a[mid] + " a[high]=" + a[hi];
|
||||
if (a[mid] > a[hi]) {
|
||||
lines.add(head + " -> " + a[mid] + " > " + a[hi] + ", the drop is right of mid, low=" + (mid + 1));
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
lines.add(head + " -> " + a[mid] + " <= " + a[hi] + ", the drop is at mid or left of it, high=" + mid);
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
lines.add("low=" + lo + " high=" + hi + " -> minimum " + a[lo] + " at index " + lo);
|
||||
return new Run(lo, lines, probes);
|
||||
}
|
||||
|
||||
/** {result, frames}: how deep the recursion went (the last frame is the empty-range base case). */
|
||||
public static int[] recursiveDepth(int[] a, int key) {
|
||||
int[] deepest = {0};
|
||||
int result = recurse(a, key, 0, a.length - 1, 1, deepest);
|
||||
return new int[] {result, deepest[0]};
|
||||
}
|
||||
|
||||
private static int recurse(int[] a, int key, int lo, int hi, int depth, int[] deepest) {
|
||||
deepest[0] = Math.max(deepest[0], depth);
|
||||
if (lo > hi) {
|
||||
return -1;
|
||||
}
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] == key) {
|
||||
return mid;
|
||||
}
|
||||
return key > a[mid]
|
||||
? recurse(a, key, mid + 1, hi, depth + 1, deepest)
|
||||
: recurse(a, key, lo, mid - 1, depth + 1, deepest);
|
||||
}
|
||||
|
||||
/** Number of elements the iterative search looks at for this key. */
|
||||
public static int probes(int[] a, int key) {
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
int probes = 0;
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
probes++;
|
||||
if (a[mid] == key) {
|
||||
return probes;
|
||||
}
|
||||
if (key > a[mid]) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return probes;
|
||||
}
|
||||
|
||||
/** Same count over the memory-free {@link Overflow.Sequence}, for sizes no array could hold. */
|
||||
public static int probes(Overflow.Sequence s, int key) {
|
||||
int lo = 0;
|
||||
int hi = s.length() - 1;
|
||||
int probes = 0;
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
probes++;
|
||||
int v = s.get(mid);
|
||||
if (v == key) {
|
||||
return probes;
|
||||
}
|
||||
if (key > v) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return probes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* The console program from the original 2015 version of the article, kept so nothing that article taught is
|
||||
* lost. Two changes: the midpoint is now {@code low + (high - low) / 2}, and the loop is a method taking a
|
||||
* Scanner and a PrintStream so a test can drive it. Run it for real with {@code java InteractiveDemo.java}.
|
||||
*/
|
||||
public final class InteractiveDemo {
|
||||
private InteractiveDemo() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
run(new Scanner(System.in), System.out, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param echo when true, every value read is printed after its prompt, as a terminal would show what you
|
||||
* typed. Needed only when input comes from a script instead of a keyboard.
|
||||
*/
|
||||
public static void run(Scanner in, PrintStream out, boolean echo) {
|
||||
out.print("Enter how many numbers to be stored: ");
|
||||
int arraySize = readInt(in, out, echo);
|
||||
|
||||
int[] numberArray = new int[arraySize];
|
||||
out.println("Enter " + arraySize + " numbers in INCREASING ORDER:");
|
||||
for (int index = 0; index < arraySize; index++) {
|
||||
out.print("Element [" + (index + 1) + "]: ");
|
||||
numberArray[index] = readInt(in, out, echo);
|
||||
}
|
||||
|
||||
String continueSearch;
|
||||
do {
|
||||
out.print("Enter the number to search: ");
|
||||
int searchKey = readInt(in, out, echo);
|
||||
|
||||
int searchResult = performBinarySearch(numberArray, searchKey);
|
||||
if (searchResult == -1) {
|
||||
out.println("Number NOT found in the array.");
|
||||
} else {
|
||||
out.println("Number " + searchKey + " found at position " + (searchResult + 1));
|
||||
}
|
||||
|
||||
out.print("Want to search another number? (y/n): ");
|
||||
continueSearch = in.next();
|
||||
if (echo) {
|
||||
out.println(continueSearch);
|
||||
}
|
||||
} while (continueSearch.equalsIgnoreCase("y"));
|
||||
}
|
||||
|
||||
private static int readInt(Scanner in, PrintStream out, boolean echo) {
|
||||
int value = in.nextInt();
|
||||
if (echo) {
|
||||
out.println(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Returns the index of {@code key} in the sorted array, or -1 (the original method, same name). */
|
||||
public static int performBinarySearch(int[] arr, int key) {
|
||||
int low = 0;
|
||||
int high = arr.length - 1;
|
||||
while (low <= high) {
|
||||
int mid = low + (high - low) / 2; // the original had (low + high) / 2
|
||||
if (arr[mid] == key) {
|
||||
return mid;
|
||||
} else if (key > arr[mid]) {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
/**
|
||||
* The remaining interview problems that are not already one call into {@link BinarySearch},
|
||||
* {@link RotatedArray} or {@link SearchOnAnswer}. The full list of ten:
|
||||
*
|
||||
* <pre>
|
||||
* 1 Search insert position BinarySearch.insertPosition
|
||||
* 2 First and last position InterviewProblems.searchRange
|
||||
* 3 Count occurrences BinarySearch.count
|
||||
* 4 Search in a rotated array RotatedArray.search
|
||||
* 5 Minimum of a rotated array RotatedArray.minIndex
|
||||
* 6 Find a peak element InterviewProblems.findPeak
|
||||
* 7 Integer square root SearchOnAnswer.sqrt
|
||||
* 8 Koko eating bananas SearchOnAnswer.minEatingSpeed
|
||||
* 9 Ship packages within D days SearchOnAnswer.shipWithinDays
|
||||
* 10 Search a 2D matrix InterviewProblems.searchMatrix
|
||||
* </pre>
|
||||
*/
|
||||
public final class InterviewProblems {
|
||||
private InterviewProblems() {}
|
||||
|
||||
/** {first, last} index of {@code key}, or {-1, -1}. Two boundary searches. */
|
||||
public static int[] searchRange(int[] a, int key) {
|
||||
return new int[] {BinarySearch.firstOccurrence(a, key), BinarySearch.lastOccurrence(a, key)};
|
||||
}
|
||||
|
||||
/**
|
||||
* Index of ANY peak: an element strictly greater than both neighbours (outside the array counts as
|
||||
* minus infinity). Adjacent elements must differ. Follow the slope upward: a peak must exist that way.
|
||||
*/
|
||||
public static int findPeak(int[] a) {
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
while (lo < hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] < a[mid + 1]) { // rising: a peak exists to the right of mid
|
||||
lo = mid + 1;
|
||||
} else { // falling (or at a peak): a peak exists at mid or to its left
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search a matrix where every row is sorted and each row starts above the end of the previous row.
|
||||
* Pretend it is one flat sorted array of rows*cols elements: index i lives at [i / cols][i % cols].
|
||||
*/
|
||||
public static boolean searchMatrix(int[][] m, int target) {
|
||||
if (m.length == 0 || m[0].length == 0) {
|
||||
return false;
|
||||
}
|
||||
int cols = m[0].length;
|
||||
int lo = 0;
|
||||
int hi = m.length * cols - 1;
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
int v = m[mid / cols][mid % cols];
|
||||
if (v == target) {
|
||||
return true;
|
||||
}
|
||||
if (target > v) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The midpoint overflow bug, reproduced at the size where it bites.
|
||||
*
|
||||
* <p>A real {@code int[]} of 2 billion elements needs about 8 GB, so the demo searches a
|
||||
* {@link Sequence}: a sorted "array" whose element {@code i} is simply {@code i}, with no memory behind
|
||||
* it. {@link Sequence#get(int)} throws the same exception type a real array would for a bad index.
|
||||
*/
|
||||
public final class Overflow {
|
||||
private Overflow() {}
|
||||
|
||||
/** A sorted sequence 0, 1, 2, ... length-1 that costs no memory. */
|
||||
public record Sequence(int length) {
|
||||
public int get(int i) {
|
||||
if (i < 0 || i >= length) {
|
||||
throw new ArrayIndexOutOfBoundsException("Index " + i + " out of bounds for length " + length);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
/** The textbook version, with {@code (lo + hi) / 2}. {@code log} (nullable) records every step. */
|
||||
public static int broken(Sequence s, int key, List<String> log) {
|
||||
int lo = 0;
|
||||
int hi = s.length() - 1;
|
||||
while (lo <= hi) {
|
||||
int mid = (lo + hi) / 2; // lo + hi can exceed Integer.MAX_VALUE and wrap to a negative number
|
||||
if (log != null) {
|
||||
log.add("lo=" + lo + " hi=" + hi + " lo+hi=" + (lo + hi) + " mid=" + mid);
|
||||
}
|
||||
int v = s.get(mid);
|
||||
if (v == key) {
|
||||
return mid;
|
||||
}
|
||||
if (key > v) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Fix 1: {@code lo + (hi - lo) / 2}. {@code hi - lo} cannot overflow because 0 <= lo <= hi. */
|
||||
public static int safeSubtract(Sequence s, int key, List<String> log) {
|
||||
int lo = 0;
|
||||
int hi = s.length() - 1;
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (log != null) {
|
||||
log.add("lo=" + lo + " hi=" + hi + " hi-lo=" + (hi - lo) + " mid=" + mid);
|
||||
}
|
||||
int v = s.get(mid);
|
||||
if (v == key) {
|
||||
return mid;
|
||||
}
|
||||
if (key > v) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Fix 2: {@code (lo + hi) >>> 1}. The sum wraps, but read as unsigned it is still correct before halving. */
|
||||
public static int safeShift(Sequence s, int key) {
|
||||
int lo = 0;
|
||||
int hi = s.length() - 1;
|
||||
while (lo <= hi) {
|
||||
int mid = (lo + hi) >>> 1;
|
||||
int v = s.get(mid);
|
||||
if (v == key) {
|
||||
return mid;
|
||||
}
|
||||
if (key > v) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Plausible-looking wrong versions. Each is one small edit away from the correct loop in
|
||||
* {@link BinarySearch}, which is exactly why these bugs survive code review. The other classic mistakes
|
||||
* (unsorted input, duplicates, the negative return value of Arrays.binarySearch) need no wrong code at all
|
||||
* and are demonstrated straight from PitfallsTest.
|
||||
*/
|
||||
public final class Pitfalls {
|
||||
private Pitfalls() {}
|
||||
|
||||
/** Bug: {@code hi = a.length} with an inclusive {@code lo <= hi} loop. Reads a[a.length]. */
|
||||
public static int hiIsLength(int[] a, int key) {
|
||||
int lo = 0;
|
||||
int hi = a.length; // should be a.length - 1
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] == key) {
|
||||
return mid;
|
||||
}
|
||||
if (key > a[mid]) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bug: {@code lo = mid} instead of {@code lo = mid + 1}. When the range shrinks to one or two elements
|
||||
* and the middle one is too small, mid equals lo, the assignment changes nothing and the loop never ends.
|
||||
* {@code cap} stops the demo.
|
||||
* Returns -2 when the cap was hit.
|
||||
*/
|
||||
public static int loEqualsMid(int[] a, int key, int cap, List<String> log) {
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
for (int iteration = 1; lo <= hi; iteration++) {
|
||||
if (iteration > cap) {
|
||||
return -2;
|
||||
}
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
log.add("iteration " + iteration + ": low=" + lo + " high=" + hi + " mid=" + mid + " a[mid]=" + a[mid]);
|
||||
if (a[mid] == key) {
|
||||
return mid;
|
||||
}
|
||||
if (a[mid] < key) {
|
||||
lo = mid; // should be mid + 1
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
/**
|
||||
* Binary search on an array that was sorted and then rotated, such as [4, 5, 6, 7, 0, 1, 2].
|
||||
* The array is no longer sorted, but at every step at least one half of it still is.
|
||||
*/
|
||||
public final class RotatedArray {
|
||||
private RotatedArray() {}
|
||||
|
||||
/** Search a rotated array of DISTINCT values. Returns the index of {@code key} or -1. */
|
||||
public static int search(int[] a, int key) {
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
while (lo <= hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] == key) {
|
||||
return mid;
|
||||
}
|
||||
if (a[lo] <= a[mid]) { // left half [lo..mid] is sorted
|
||||
if (a[lo] <= key && key < a[mid]) {
|
||||
hi = mid - 1;
|
||||
} else {
|
||||
lo = mid + 1;
|
||||
}
|
||||
} else { // right half [mid..hi] is sorted
|
||||
if (a[mid] < key && key <= a[hi]) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Index of the smallest element (the rotation point) of a rotated array of DISTINCT values. */
|
||||
public static int minIndex(int[] a) {
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
while (lo < hi) {
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] > a[hi]) { // the minimum is strictly to the right of mid
|
||||
lo = mid + 1;
|
||||
} else { // a[mid] <= a[hi]: the minimum is at mid or to its left
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Smallest value when duplicates are allowed. Returns {value, iterations}. When a[mid] == a[hi]
|
||||
* the comparison proves nothing, so the only safe move is {@code hi--}: the worst case is O(n).
|
||||
*/
|
||||
public static int[] minWithDuplicates(int[] a) {
|
||||
int lo = 0;
|
||||
int hi = a.length - 1;
|
||||
int iterations = 0;
|
||||
while (lo < hi) {
|
||||
iterations++;
|
||||
int mid = lo + (hi - lo) / 2;
|
||||
if (a[mid] > a[hi]) {
|
||||
lo = mid + 1;
|
||||
} else if (a[mid] < a[hi]) {
|
||||
hi = mid;
|
||||
} else {
|
||||
hi--;
|
||||
}
|
||||
}
|
||||
return new int[] {a[lo], iterations};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import java.util.function.LongPredicate;
|
||||
|
||||
/**
|
||||
* "Binary search on the answer": there is no array to search, but the answer lives in a range and a yes/no
|
||||
* question about a candidate flips from false to true exactly once. Searching that flip point is the same
|
||||
* loop as {@link BinarySearch#lowerBound(int[], int)}.
|
||||
*/
|
||||
public final class SearchOnAnswer {
|
||||
private SearchOnAnswer() {}
|
||||
|
||||
/**
|
||||
* Smallest x in [lo, hi] for which {@code ok} is true. Requires: ok is false...false true...true over
|
||||
* the range, and ok(hi) is true.
|
||||
*/
|
||||
public static long firstTrue(long lo, long hi, LongPredicate ok) {
|
||||
while (lo < hi) {
|
||||
long mid = lo + (hi - lo) / 2;
|
||||
if (ok.test(mid)) {
|
||||
hi = mid; // mid might be the answer: keep it
|
||||
} else {
|
||||
lo = mid + 1; // mid is too small: drop it
|
||||
}
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
/** Integer square root, rounded down, without Math.sqrt: the largest m with m*m <= x. */
|
||||
public static int sqrt(int x, LongPredicate probe) {
|
||||
long firstTooBig = firstTrue(0, (long) x + 1, probe);
|
||||
return (int) (firstTooBig - 1);
|
||||
}
|
||||
|
||||
public static int sqrt(int x) {
|
||||
return sqrt(x, m -> m * m > x);
|
||||
}
|
||||
|
||||
/** Smallest eating speed (bananas per hour) that finishes every pile within {@code h} hours. */
|
||||
public static int minEatingSpeed(int[] piles, int h, LongPredicate probe) {
|
||||
long max = 0;
|
||||
for (int p : piles) {
|
||||
max = Math.max(max, p);
|
||||
}
|
||||
return (int) firstTrue(1, max, probe);
|
||||
}
|
||||
|
||||
public static int minEatingSpeed(int[] piles, int h) {
|
||||
return minEatingSpeed(piles, h, k -> hoursNeeded(piles, k) <= h);
|
||||
}
|
||||
|
||||
static long hoursNeeded(int[] piles, long speed) {
|
||||
long hours = 0;
|
||||
for (int p : piles) {
|
||||
hours += (p + speed - 1) / speed; // ceil(p / speed)
|
||||
}
|
||||
return hours;
|
||||
}
|
||||
|
||||
/** Smallest ship capacity that moves the packages, in order, within {@code days} days. */
|
||||
public static int shipWithinDays(int[] weights, int days, LongPredicate probe) {
|
||||
long max = 0;
|
||||
long sum = 0;
|
||||
for (int w : weights) {
|
||||
max = Math.max(max, w);
|
||||
sum += w;
|
||||
}
|
||||
return (int) firstTrue(max, sum, probe);
|
||||
}
|
||||
|
||||
public static int shipWithinDays(int[] weights, int days) {
|
||||
return shipWithinDays(weights, days, cap -> daysNeeded(weights, cap) <= days);
|
||||
}
|
||||
|
||||
static int daysNeeded(int[] weights, long capacity) {
|
||||
int days = 1;
|
||||
long load = 0;
|
||||
for (int w : weights) {
|
||||
if (load + w > capacity) {
|
||||
days++;
|
||||
load = 0;
|
||||
}
|
||||
load += w;
|
||||
}
|
||||
return days;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BoundsTest {
|
||||
static final int[] A = {1, 2, 2, 2, 2, 2, 3, 5, 5, 8};
|
||||
|
||||
@Test
|
||||
void lowerAndUpperBoundOnDuplicates() {
|
||||
Transcript t = Transcript.start("04-lower-upper-bound.txt",
|
||||
"lowerBound / upperBound on " + Arrays.toString(A) + " (indexes 0..9)");
|
||||
t.line(String.format("%3s | %10s | %10s | %5s | %4s | %5s | %9s | %19s",
|
||||
"key", "lowerBound", "upperBound", "first", "last", "count", "iterative", "Arrays.binarySearch"));
|
||||
for (int key : new int[] {0, 1, 2, 3, 4, 5, 8, 9}) {
|
||||
int lb = BinarySearch.lowerBound(A, key);
|
||||
int ub = BinarySearch.upperBound(A, key);
|
||||
int first = BinarySearch.firstOccurrence(A, key);
|
||||
int last = BinarySearch.lastOccurrence(A, key);
|
||||
int count = BinarySearch.count(A, key);
|
||||
assertEquals(BruteForce.searchInsert(A, key), lb);
|
||||
assertEquals(BruteForce.searchRange(A, key)[0], first);
|
||||
assertEquals(BruteForce.searchRange(A, key)[1], last);
|
||||
assertEquals(BruteForce.count(A, key), count);
|
||||
assertEquals(ub - lb, count);
|
||||
t.line(String.format("%3d | %10d | %10d | %5d | %4d | %5d | %9d | %19d",
|
||||
key, lb, ub, first, last, count, BinarySearch.iterative(A, key), Arrays.binarySearch(A, key)));
|
||||
}
|
||||
t.blank();
|
||||
for (int key : new int[] {2, 4}) {
|
||||
DryRuns.Run r = DryRuns.lowerBound(A, key);
|
||||
assertEquals(BinarySearch.lowerBound(A, key), r.result());
|
||||
t.line("lowerBound for " + key + ":");
|
||||
r.lines().forEach(l -> t.line(" " + l));
|
||||
t.blank();
|
||||
}
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.Locale;
|
||||
import java.util.Random;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Counted, not timed: how many elements each search looks at. */
|
||||
class ComplexityTest {
|
||||
@Test
|
||||
void probesGrowWithLogN() {
|
||||
Transcript t = Transcript.start("09-operation-counts.txt",
|
||||
"Elements looked at: linear scan vs binary search (counted, not timed)");
|
||||
t.line(String.format("%13s | %24s | %30s | %s", "n", "linear scan, absent key", "binary, worst over every key", "floor(log2 n) + 1"));
|
||||
for (int n : new int[] {10, 1_000, 100_000, 1_000_000}) {
|
||||
int[] a = DryRunTest.evens(n);
|
||||
int worst = 0;
|
||||
for (int key = -1; key <= 2 * n; key++) { // every present key, every gap, both ends
|
||||
worst = Math.max(worst, DryRuns.probes(a, key));
|
||||
}
|
||||
int bound = 32 - Integer.numberOfLeadingZeros(n);
|
||||
assertEquals(bound, worst, "n=" + n);
|
||||
t.line(String.format(Locale.ROOT, "%,13d | %,24d | %,30d | %d", n, n, worst, bound));
|
||||
}
|
||||
t.blank();
|
||||
|
||||
Overflow.Sequence big = new Overflow.Sequence(1_000_000_000);
|
||||
Random rnd = new Random(2026);
|
||||
int worst = Math.max(DryRuns.probes(big, -1), DryRuns.probes(big, 1_000_000_000));
|
||||
for (int i = 0; i < 10_000; i++) {
|
||||
worst = Math.max(worst, DryRuns.probes(big, rnd.nextInt(1_000_002) * 1000 - 1));
|
||||
}
|
||||
assertTrue(worst <= 30);
|
||||
t.line(String.format(Locale.ROOT, "n=%,d (memory-free Sequence): the most probes seen over 10,002 sampled keys = %d; floor(log2 n) + 1 = %d",
|
||||
1_000_000_000, worst, 32 - Integer.numberOfLeadingZeros(1_000_000_000)));
|
||||
t.line(String.format(Locale.ROOT, "a linear scan of the same data would look at up to %,d elements", 1_000_000_000));
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.Locale;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Traces for the three searches the original article walked through, plus recursive vs iterative. */
|
||||
class DryRunTest {
|
||||
static final int[] SAMPLE = {10, 20, 30, 40, 45};
|
||||
|
||||
static int[] evens(int n) {
|
||||
int[] a = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
a[i] = 2 * i;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
@Test
|
||||
void tracesTheThreeSearchesFromTheOriginalArticle() {
|
||||
Transcript t = Transcript.start("01-dry-run-iterative.txt",
|
||||
"Iterative binary search, traced step by step on [10, 20, 30, 40, 45]");
|
||||
int[][] cases = {{40, 3}, {10, 0}, {25, -1}};
|
||||
for (int[] c : cases) {
|
||||
DryRuns.Run r = DryRuns.iterative(SAMPLE, c[0]);
|
||||
assertEquals(c[1], r.result());
|
||||
assertEquals(BinarySearch.iterative(SAMPLE, c[0]), r.result(), "trace must match the real code");
|
||||
t.line("search for " + c[0]);
|
||||
r.lines().forEach(l -> t.line(" " + l));
|
||||
String where = r.result() >= 0 ? " (position " + (r.result() + 1) + " counting from 1)" : "";
|
||||
t.line(" result: " + r.result() + where + ", " + r.probes() + " elements compared").blank();
|
||||
}
|
||||
t.flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursiveAndIterativeAgreeAndRecursionStaysShallow() {
|
||||
Transcript t = Transcript.start("02-recursive-vs-iterative.txt",
|
||||
"Recursive vs iterative: same answers, and how deep the recursion goes");
|
||||
int[] a = evens(1000);
|
||||
int checked = 0;
|
||||
for (int key = -1; key <= 2001; key++) {
|
||||
assertEquals(BinarySearch.iterative(a, key), BinarySearch.recursive(a, key), "key " + key);
|
||||
checked++;
|
||||
}
|
||||
t.line("n=1000, elements 0,2,4,...,1998: " + checked + " keys from -1 to 2001 (present and absent)");
|
||||
t.line("give identical answers from the iterative and the recursive version.").blank();
|
||||
for (int n : new int[] {10, 1000, 1_000_000}) {
|
||||
int[] arr = evens(n);
|
||||
int key = arr[n - 1] + 1; // absent, larger than everything: the longest path
|
||||
int[] r = DryRuns.recursiveDepth(arr, key);
|
||||
assertEquals(-1, r[0]);
|
||||
t.line(String.format(Locale.ROOT,
|
||||
"n=%,9d absent key above the last element: result=%d, recursion frames=%d (iterative uses 0 extra frames)",
|
||||
n, r[0], r[1]));
|
||||
}
|
||||
t.flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sixteenValuesNeedFourProbes() {
|
||||
int[] a = new int[16];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
a[i] = 2 * (i + 1);
|
||||
}
|
||||
DryRuns.Run r = DryRuns.iterative(a, 26);
|
||||
assertEquals(12, r.result());
|
||||
assertEquals(4, r.probes());
|
||||
Transcript t = Transcript.start("13-sixteen-elements.txt", "Searching for 26 among 2, 4, 6, ... 32 (sixteen values, indexes 0..15)");
|
||||
r.lines().forEach(l -> t.line(l));
|
||||
t.line("result: index " + r.result() + " after " + r.probes() + " elements compared; a linear scan needs 13").flush();
|
||||
assertEquals(13, BruteForce.indexOf(a, 26) + 1);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Scanner;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class InteractiveDemoTest {
|
||||
/** The sample run printed in the original 2015 article, character for character. */
|
||||
private static final String ORIGINAL_SAMPLE = String.join("\n",
|
||||
"Enter how many numbers to be stored: 5",
|
||||
"Enter 5 numbers in INCREASING ORDER:",
|
||||
"Element [1]: 10",
|
||||
"Element [2]: 20",
|
||||
"Element [3]: 30",
|
||||
"Element [4]: 40",
|
||||
"Element [5]: 45",
|
||||
"Enter the number to search: 40",
|
||||
"Number 40 found at position 4",
|
||||
"Want to search another number? (y/n): y",
|
||||
"Enter the number to search: 10",
|
||||
"Number 10 found at position 1",
|
||||
"Want to search another number? (y/n): y",
|
||||
"Enter the number to search: 25",
|
||||
"Number NOT found in the array.",
|
||||
"Want to search another number? (y/n): n",
|
||||
"");
|
||||
|
||||
@Test
|
||||
void reproducesTheOriginalSampleSession() {
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
PrintStream out = new PrintStream(buffer, true, StandardCharsets.UTF_8);
|
||||
InteractiveDemo.run(new Scanner("5 10 20 30 40 45 40 y 10 y 25 n"), out, true);
|
||||
String session = buffer.toString(StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||
assertEquals(ORIGINAL_SAMPLE, session);
|
||||
|
||||
Transcript t = Transcript.start("11-interactive-session.txt",
|
||||
"InteractiveDemo (the original console program) with scripted input; values echoed like a terminal");
|
||||
for (String line : session.split("\n")) {
|
||||
t.line(line);
|
||||
}
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.TreeSet;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Reads the JDK's own source instead of trusting memory about how java.util does it. */
|
||||
class JdkSourceTest {
|
||||
@Test
|
||||
void jdkUsesUnsignedShiftForTheMidpoint() throws IOException {
|
||||
Path zip = Path.of(System.getProperty("java.home"), "lib", "src.zip");
|
||||
assumeTrue(Files.exists(zip), "this JDK has no lib/src.zip");
|
||||
Transcript t = Transcript.start("12-jdk-source.txt", "How the JDK itself computes the midpoint (read from this JDK's lib/src.zip)");
|
||||
t.line("JDK: " + Runtime.version()).blank();
|
||||
try (var fs = FileSystems.newFileSystem(zip)) {
|
||||
List<String> arrays = Files.readAllLines(fs.getPath("java.base/java/util/Arrays.java"));
|
||||
int start = -1;
|
||||
for (int i = 0; i < arrays.size(); i++) {
|
||||
if (arrays.get(i).contains("private static int binarySearch0(int[] a, int fromIndex, int toIndex,")) {
|
||||
start = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertTrue(start >= 0, "binarySearch0(int[]) not found");
|
||||
t.line("java/util/Arrays.java, binarySearch0(int[] ...), lines " + (start + 1) + " onwards:");
|
||||
boolean sawShift = false;
|
||||
for (int i = start; i < arrays.size(); i++) {
|
||||
String line = arrays.get(i);
|
||||
t.line(String.format("%5d %s", i + 1, line));
|
||||
sawShift |= line.contains("(low + high) >>> 1");
|
||||
if (line.equals(" }")) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertTrue(sawShift, "expected (low + high) >>> 1 in Arrays.binarySearch0");
|
||||
t.blank();
|
||||
|
||||
List<String> collections = Files.readAllLines(fs.getPath("java.base/java/util/Collections.java"));
|
||||
int decl = -1;
|
||||
for (int i = 0; i < collections.size(); i++) {
|
||||
if (collections.get(i).contains("private static <T> int indexedBinarySearch(")) {
|
||||
decl = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertTrue(decl >= 0, "indexedBinarySearch not found");
|
||||
t.line("java/util/Collections.java, indexedBinarySearch(...):");
|
||||
for (int i = decl; i < collections.size(); i++) {
|
||||
String line = collections.get(i);
|
||||
if (line.contains("int mid")) {
|
||||
t.line(String.format("%5d %s", i + 1, line));
|
||||
assertTrue(line.contains(">>> 1"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
t.flush();
|
||||
}
|
||||
|
||||
@Test
|
||||
void jdkHasNoLowerOrUpperBound() {
|
||||
Transcript t = Transcript.start("14-no-bound-methods.txt",
|
||||
"Public methods with \"bound\" or \"binarySearch\" in their name on java.util.Arrays, Collections and List");
|
||||
t.line("JDK: " + Runtime.version()).blank();
|
||||
for (Class<?> c : new Class<?>[] {java.util.Arrays.class, java.util.Collections.class, java.util.List.class}) {
|
||||
TreeSet<String> bound = new TreeSet<>();
|
||||
TreeSet<String> search = new TreeSet<>();
|
||||
int overloads = 0;
|
||||
for (Method m : c.getMethods()) {
|
||||
String n = m.getName().toLowerCase(java.util.Locale.ROOT);
|
||||
if (n.contains("bound")) {
|
||||
bound.add(m.getName());
|
||||
}
|
||||
if (n.startsWith("binarysearch")) {
|
||||
search.add(m.getName());
|
||||
overloads++;
|
||||
}
|
||||
}
|
||||
assertTrue(bound.isEmpty(), c.getName() + " unexpectedly has " + bound);
|
||||
t.line(String.format("%-24s methods named *bound*: %s binarySearch overloads: %d", c.getName(), bound, overloads));
|
||||
}
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class OverflowTest {
|
||||
@Test
|
||||
void midpointOverflowAtTwoBillionElements() {
|
||||
Transcript t = Transcript.start("03-overflow-mid.txt",
|
||||
"The (lo + hi) / 2 bug on a sorted sequence of 2,000,000,000 elements (no array: see Overflow.Sequence)");
|
||||
|
||||
int lo = 1_000_000_000;
|
||||
int hi = 1_999_999_999;
|
||||
assertTrue(lo + hi < 0);
|
||||
t.line("Plain int arithmetic, lo=" + lo + " hi=" + hi + ":");
|
||||
t.line(" lo + hi = " + (lo + hi));
|
||||
t.line(" (lo + hi) / 2 = " + ((lo + hi) / 2));
|
||||
t.line(" lo + (hi - lo) / 2 = " + (lo + (hi - lo) / 2));
|
||||
t.line(" (lo + hi) >>> 1 = " + ((lo + hi) >>> 1));
|
||||
assertEquals(1_499_999_999, lo + (hi - lo) / 2);
|
||||
assertEquals(1_499_999_999, (lo + hi) >>> 1);
|
||||
t.blank();
|
||||
|
||||
Overflow.Sequence s = new Overflow.Sequence(2_000_000_000);
|
||||
int key = 1_999_999_999; // the last element
|
||||
|
||||
List<String> brokenLog = new ArrayList<>();
|
||||
ArrayIndexOutOfBoundsException ex =
|
||||
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Overflow.broken(s, key, brokenLog));
|
||||
t.line("Broken (lo + hi) / 2, searching for the last element, " + key + ":");
|
||||
brokenLog.forEach(l -> t.line(" " + l));
|
||||
t.line(" -> " + ex.getClass().getName() + ": " + ex.getMessage()).blank();
|
||||
|
||||
List<String> fixedLog = new ArrayList<>();
|
||||
int found = Overflow.safeSubtract(s, key, fixedLog);
|
||||
assertEquals(key, found);
|
||||
t.line("Fixed with lo + (hi - lo) / 2: found index " + found + " after " + fixedLog.size() + " steps. First and last steps:");
|
||||
t.line(" " + fixedLog.get(0));
|
||||
t.line(" " + fixedLog.get(1));
|
||||
t.line(" ...");
|
||||
t.line(" " + fixedLog.get(fixedLog.size() - 1)).blank();
|
||||
|
||||
assertEquals(key, Overflow.safeShift(s, key));
|
||||
t.line("Fixed with (lo + hi) >>> 1: found index " + Overflow.safeShift(s, key));
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PitfallsTest {
|
||||
@Test
|
||||
void sixClassicMistakesEachReproduced() {
|
||||
Transcript t = Transcript.start("10-pitfalls.txt", "Six classic binary-search mistakes, each reproduced");
|
||||
|
||||
int[] three = {1, 3, 5};
|
||||
ArrayIndexOutOfBoundsException ex =
|
||||
assertThrows(ArrayIndexOutOfBoundsException.class, () -> Pitfalls.hiIsLength(three, 9));
|
||||
t.line("1. hi = a.length with lo <= hi, searching " + Arrays.toString(three) + " for 9");
|
||||
t.line(" " + ex.getClass().getName() + ": " + ex.getMessage());
|
||||
t.line(" correct version returns " + BinarySearch.iterative(three, 9)).blank();
|
||||
|
||||
int[] two = {1, 2};
|
||||
List<String> log = new ArrayList<>();
|
||||
int stuck = Pitfalls.loEqualsMid(two, 2, 6, log);
|
||||
assertEquals(-2, stuck);
|
||||
t.line("2. lo = mid instead of lo = mid + 1, searching " + Arrays.toString(two) + " for 2 (stopped after 6 iterations)");
|
||||
log.forEach(l -> t.line(" " + l));
|
||||
t.line(" correct version returns " + BinarySearch.iterative(two, 2)).blank();
|
||||
|
||||
int[] unsorted = {5, 1, 2, 9, 3};
|
||||
assertEquals(-1, BinarySearch.iterative(unsorted, 3));
|
||||
assertEquals(4, BruteForce.indexOf(unsorted, 3));
|
||||
t.line("3. unsorted input " + Arrays.toString(unsorted) + ", key 3");
|
||||
t.line(" binary search returns " + BinarySearch.iterative(unsorted, 3) + ", a linear scan returns " + BruteForce.indexOf(unsorted, 3)).blank();
|
||||
|
||||
int[] dups = {1, 2, 2, 2, 2, 2, 3};
|
||||
t.line("4. duplicates " + Arrays.toString(dups) + ", key 2 occurs at indexes 1..5");
|
||||
t.line(" iterative returns " + BinarySearch.iterative(dups, 2)
|
||||
+ ", Arrays.binarySearch returns " + Arrays.binarySearch(dups, 2)
|
||||
+ ", firstOccurrence returns " + BinarySearch.firstOccurrence(dups, 2)
|
||||
+ ", lastOccurrence returns " + BinarySearch.lastOccurrence(dups, 2)).blank();
|
||||
|
||||
int[] a = {10, 20, 30, 40, 45};
|
||||
t.line("5. Arrays.binarySearch does not return -1 for \"not found\": it returns -(insertion point) - 1");
|
||||
for (int key : new int[] {25, 5, 50}) {
|
||||
int r = Arrays.binarySearch(a, key);
|
||||
assertEquals(-BinarySearch.insertPosition(a, key) - 1, r);
|
||||
t.line(String.format(" Arrays.binarySearch(%s, %d) = %d (== -1? %b) insertion point = %d",
|
||||
Arrays.toString(a), key, r, r == -1, -r - 1));
|
||||
}
|
||||
t.blank();
|
||||
|
||||
t.line("6. overflow of (lo + hi) / 2: see 03-overflow-mid.txt");
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Random;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Seeded random inputs: every fast solution must agree with its brute-force reference. */
|
||||
class RandomAgreementTest {
|
||||
private static final int CASES = 3000;
|
||||
private final Random rnd = new Random(2026);
|
||||
private final Transcript t = Transcript.start("08-random-agreement.txt",
|
||||
"Seeded random cross-check (Random(2026)): fast solution vs brute force");
|
||||
|
||||
private int[] sortedWithDuplicates() {
|
||||
int[] a = new int[rnd.nextInt(16)];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
a[i] = rnd.nextInt(13) - 2;
|
||||
}
|
||||
Arrays.sort(a);
|
||||
return a;
|
||||
}
|
||||
|
||||
private int[] distinctSorted(int maxLen) {
|
||||
int[] a = new int[1 + rnd.nextInt(maxLen)];
|
||||
int v = rnd.nextInt(5) - 3;
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
v += 1 + rnd.nextInt(4);
|
||||
a[i] = v;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
private static int[] rotate(int[] a, int k) {
|
||||
int[] r = new int[a.length];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
r[i] = a[(i + k) % a.length];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
private void report(String name, int cases) {
|
||||
t.line(String.format(Locale.ROOT, "%-58s %,6d cases 0 disagreements", name, cases));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyProblemAgreesWithBruteForce() {
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] a = sortedWithDuplicates();
|
||||
int key = rnd.nextInt(18) - 3;
|
||||
assertEquals(BruteForce.searchInsert(a, key), BinarySearch.insertPosition(a, key), Arrays.toString(a) + " " + key);
|
||||
int idx = BinarySearch.iterative(a, key);
|
||||
assertEquals(BruteForce.indexOf(a, key) >= 0, idx >= 0);
|
||||
if (idx >= 0) {
|
||||
assertEquals(key, a[idx]);
|
||||
}
|
||||
assertEquals(idx, BinarySearch.recursive(a, key));
|
||||
}
|
||||
report("plain search + insert position (1)", CASES);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] a = sortedWithDuplicates();
|
||||
int key = rnd.nextInt(18) - 3;
|
||||
assertArrayEquals(BruteForce.searchRange(a, key), InterviewProblems.searchRange(a, key), Arrays.toString(a) + " " + key);
|
||||
}
|
||||
report("first and last position (2)", CASES);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] a = sortedWithDuplicates();
|
||||
int key = rnd.nextInt(18) - 3;
|
||||
assertEquals(BruteForce.count(a, key), BinarySearch.count(a, key), Arrays.toString(a) + " " + key);
|
||||
}
|
||||
report("count occurrences (3)", CASES);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] sorted = distinctSorted(14);
|
||||
int[] a = rotate(sorted, rnd.nextInt(sorted.length));
|
||||
int key = sorted[0] - 1 + rnd.nextInt(sorted[sorted.length - 1] - sorted[0] + 3);
|
||||
assertEquals(BruteForce.indexOf(a, key), RotatedArray.search(a, key), Arrays.toString(a) + " " + key);
|
||||
}
|
||||
report("search in rotated array (4)", CASES);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] sorted = distinctSorted(14);
|
||||
int[] a = rotate(sorted, rnd.nextInt(sorted.length));
|
||||
assertEquals(BruteForce.minIndex(a), RotatedArray.minIndex(a), Arrays.toString(a));
|
||||
}
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] sorted = new int[1 + rnd.nextInt(14)];
|
||||
for (int i = 0; i < sorted.length; i++) {
|
||||
sorted[i] = rnd.nextInt(4);
|
||||
}
|
||||
Arrays.sort(sorted);
|
||||
int[] a = rotate(sorted, rnd.nextInt(sorted.length));
|
||||
assertEquals(a[BruteForce.minIndex(a)], RotatedArray.minWithDuplicates(a)[0], Arrays.toString(a));
|
||||
}
|
||||
report("minimum of rotated array, distinct + duplicates (5)", 2 * CASES);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] a = new int[1 + rnd.nextInt(12)];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
do {
|
||||
a[i] = rnd.nextInt(10);
|
||||
} while (i > 0 && a[i] == a[i - 1]);
|
||||
}
|
||||
assertTrue(BruteForce.isPeak(a, InterviewProblems.findPeak(a)), Arrays.toString(a));
|
||||
}
|
||||
report("find a peak element (6)", CASES);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int x = rnd.nextInt(100_001);
|
||||
assertEquals(BruteForce.sqrt(x), SearchOnAnswer.sqrt(x), "x=" + x);
|
||||
}
|
||||
for (int c = 0; c < 1000; c++) {
|
||||
int x = Integer.MAX_VALUE - rnd.nextInt(1_000_000);
|
||||
int r = SearchOnAnswer.sqrt(x);
|
||||
assertTrue((long) r * r <= x && (long) (r + 1) * (r + 1) > x, "x=" + x);
|
||||
}
|
||||
report("integer square root, small + near Integer.MAX_VALUE (7)", CASES + 1000);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] piles = new int[1 + rnd.nextInt(5)];
|
||||
int sum = 0;
|
||||
for (int i = 0; i < piles.length; i++) {
|
||||
piles[i] = 1 + rnd.nextInt(12);
|
||||
sum += piles[i];
|
||||
}
|
||||
int h = piles.length + rnd.nextInt(sum - piles.length + 3);
|
||||
assertEquals(BruteForce.minEatingSpeed(piles, h), SearchOnAnswer.minEatingSpeed(piles, h), Arrays.toString(piles) + " h=" + h);
|
||||
}
|
||||
report("koko eating bananas (8)", CASES);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int[] w = new int[1 + rnd.nextInt(8)];
|
||||
for (int i = 0; i < w.length; i++) {
|
||||
w[i] = 1 + rnd.nextInt(10);
|
||||
}
|
||||
int days = 1 + rnd.nextInt(w.length);
|
||||
assertEquals(BruteForce.shipWithinDays(w, days), SearchOnAnswer.shipWithinDays(w, days), Arrays.toString(w) + " days=" + days);
|
||||
}
|
||||
report("ship packages within D days (9)", CASES);
|
||||
|
||||
for (int c = 0; c < CASES; c++) {
|
||||
int rows = 1 + rnd.nextInt(4);
|
||||
int cols = 1 + rnd.nextInt(4);
|
||||
int[][] m = new int[rows][cols];
|
||||
int v = rnd.nextInt(3);
|
||||
for (int r = 0; r < rows; r++) {
|
||||
for (int k = 0; k < cols; k++) {
|
||||
v += 1 + rnd.nextInt(3);
|
||||
m[r][k] = v;
|
||||
}
|
||||
}
|
||||
int target = rnd.nextInt(v + 3) - 1;
|
||||
assertEquals(BruteForce.searchMatrix(m, target), InterviewProblems.searchMatrix(m, target), Arrays.deepToString(m) + " " + target);
|
||||
}
|
||||
report("search a 2D matrix (10)", CASES);
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.Locale;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RotatedTest {
|
||||
static final int[] R = {4, 5, 6, 7, 0, 1, 2};
|
||||
|
||||
@Test
|
||||
void tracesAndExhaustiveCheck() {
|
||||
Transcript t = Transcript.start("05-rotated-array.txt", "Rotated sorted array [4, 5, 6, 7, 0, 1, 2]");
|
||||
for (int key : new int[] {0, 3}) {
|
||||
DryRuns.Run r = DryRuns.rotatedSearch(R, key);
|
||||
assertEquals(RotatedArray.search(R, key), r.result());
|
||||
assertEquals(BruteForce.indexOf(R, key), r.result());
|
||||
t.line("search for " + key);
|
||||
r.lines().forEach(l -> t.line(" " + l));
|
||||
t.blank();
|
||||
}
|
||||
DryRuns.Run m = DryRuns.rotatedMin(R);
|
||||
assertEquals(RotatedArray.minIndex(R), m.result());
|
||||
assertEquals(4, m.result());
|
||||
t.line("find the minimum (the rotation point)");
|
||||
m.lines().forEach(l -> t.line(" " + l));
|
||||
t.blank();
|
||||
|
||||
int checks = 0;
|
||||
for (int n = 1; n <= 12; n++) {
|
||||
for (int k = 0; k < n; k++) {
|
||||
int[] a = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
a[i] = ((i + k) % n) * 3 + 1; // distinct, rotated by k
|
||||
}
|
||||
assertEquals(BruteForce.minIndex(a), RotatedArray.minIndex(a));
|
||||
for (int key = 0; key <= 3 * n + 2; key++) {
|
||||
assertEquals(BruteForce.indexOf(a, key), RotatedArray.search(a, key));
|
||||
checks++;
|
||||
}
|
||||
}
|
||||
}
|
||||
t.line("exhaustive check, every rotation of every distinct array of length 1..12, every key: " + checks + " searches, 0 disagreements").blank();
|
||||
|
||||
t.line("With duplicates the same idea can degrade to a linear scan (iterations of the find-minimum loop):");
|
||||
for (int n : new int[] {16, 256, 4096}) {
|
||||
int[] dup = new int[n];
|
||||
java.util.Arrays.fill(dup, 1);
|
||||
dup[1] = 0; // [1, 0, 1, 1, ..., 1]
|
||||
int[] distinct = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
distinct[i] = (i + n - 1) % n; // minimum also at index 1
|
||||
}
|
||||
int[] d = RotatedArray.minWithDuplicates(dup);
|
||||
int distinctIterations = DryRuns.rotatedMin(distinct).probes();
|
||||
assertEquals(0, d[0]);
|
||||
assertTrue(d[1] >= n / 2, "duplicates should force a near-linear scan");
|
||||
assertTrue(distinctIterations <= 13);
|
||||
t.line(String.format(Locale.ROOT, " n=%5d minimum at index 1: distinct values %2d iterations many duplicates %5d iterations",
|
||||
n, distinctIterations, d[1]));
|
||||
}
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.Locale;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SearchOnAnswerTest {
|
||||
@Test
|
||||
void sqrtKokoAndShipsWithPredicateCounts() {
|
||||
Transcript t = Transcript.start("06-search-on-answer.txt",
|
||||
"Binary search on the answer: how many times the yes/no question was asked");
|
||||
|
||||
t.line("Integer square root = largest m with m*m <= x; the question is \"is m*m > x?\"");
|
||||
for (int x : new int[] {8, 16, 1_000_000_007, Integer.MAX_VALUE}) {
|
||||
long[] calls = {0};
|
||||
int r = SearchOnAnswer.sqrt(x, m -> {
|
||||
calls[0]++;
|
||||
return m * m > x;
|
||||
});
|
||||
assertEquals(SearchOnAnswer.sqrt(x), r);
|
||||
assertEquals(BruteForce.sqrt(x), r);
|
||||
assertEquals((int) Math.sqrt(x), r);
|
||||
t.line(String.format(Locale.ROOT, " sqrt(%,d) = %d asked %d times, instead of trying up to %,d candidates",
|
||||
x, r, calls[0], (long) x + 1));
|
||||
}
|
||||
t.blank();
|
||||
|
||||
t.line("Koko eating bananas: smallest speed k with sum(ceil(pile / k)) <= h");
|
||||
int[][] pileSets = {{3, 6, 7, 11}, {30, 11, 23, 4, 20}, {30, 11, 23, 4, 20}};
|
||||
int[] hs = {8, 5, 6};
|
||||
for (int i = 0; i < pileSets.length; i++) {
|
||||
int[] piles = pileSets[i];
|
||||
int h = hs[i];
|
||||
long[] calls = {0};
|
||||
int r = SearchOnAnswer.minEatingSpeed(piles, h, k -> {
|
||||
calls[0]++;
|
||||
return SearchOnAnswer.hoursNeeded(piles, k) <= h;
|
||||
});
|
||||
assertEquals(BruteForce.minEatingSpeed(piles, h), r);
|
||||
t.line(String.format(Locale.ROOT, " piles=%s h=%d -> speed %d asked %d times (candidates 1..%d)",
|
||||
java.util.Arrays.toString(piles), h, r, calls[0], java.util.Arrays.stream(piles).max().getAsInt()));
|
||||
}
|
||||
int[] demo = {3, 6, 7, 11};
|
||||
StringBuilder hoursRow = new StringBuilder();
|
||||
StringBuilder okRow = new StringBuilder();
|
||||
for (int k = 1; k <= 11; k++) {
|
||||
long hrs = SearchOnAnswer.hoursNeeded(demo, k);
|
||||
hoursRow.append(hrs).append(k < 11 ? ", " : "");
|
||||
okRow.append(hrs <= 8 ? "T" : "F").append(k < 11 ? " " : "");
|
||||
}
|
||||
assertEquals("F F F T T T T T T T T", okRow.toString());
|
||||
t.line(" for [3, 6, 7, 11], hours needed at speed 1..11: " + hoursRow);
|
||||
t.line(" is that <= 8? " + okRow);
|
||||
int[] big = {1_000_000_000, 999_999_999, 500_000_000};
|
||||
long[] calls = {0};
|
||||
int h = 10;
|
||||
int speed = SearchOnAnswer.minEatingSpeed(big, h, k -> {
|
||||
calls[0]++;
|
||||
return SearchOnAnswer.hoursNeeded(big, k) <= h;
|
||||
});
|
||||
assertTrue(SearchOnAnswer.hoursNeeded(big, speed) <= h);
|
||||
assertFalse(SearchOnAnswer.hoursNeeded(big, speed - 1) <= h);
|
||||
t.line(String.format(Locale.ROOT,
|
||||
" piles=%s h=%d -> speed %,d asked %d times (candidates 1..1,000,000,000); checked: speed-1 needs %d hours",
|
||||
java.util.Arrays.toString(big), h, speed, calls[0], SearchOnAnswer.hoursNeeded(big, speed - 1)));
|
||||
t.blank();
|
||||
|
||||
t.line("Ship packages within D days: smallest capacity so that, loading in order, D days are enough");
|
||||
int[] weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||
long[] shipCalls = {0};
|
||||
int cap = SearchOnAnswer.shipWithinDays(weights, 5, c -> {
|
||||
shipCalls[0]++;
|
||||
return SearchOnAnswer.daysNeeded(weights, c) <= 5;
|
||||
});
|
||||
assertEquals(BruteForce.shipWithinDays(weights, 5), cap);
|
||||
t.line(String.format(Locale.ROOT, " weights=%s days=5 -> capacity %d asked %d times (candidates 10..55)",
|
||||
java.util.Arrays.toString(weights), cap, shipCalls[0]));
|
||||
t.line(" days needed at capacity " + cap + ": " + SearchOnAnswer.daysNeeded(weights, cap)
|
||||
+ "; at capacity " + (cap - 1) + ": " + SearchOnAnswer.daysNeeded(weights, cap - 1));
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.ankurm.interviewlab.binarysearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.ankurm.interviewlab.binarysearch.support.Transcript;
|
||||
import java.util.Arrays;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class TenProblemsTest {
|
||||
private static String row(int n, String name, String input, Object fast, Object brute) {
|
||||
return String.format("%2d. %-30s %-44s fast=%-10s brute-force=%s", n, name, input, fast, brute);
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneExampleEach() {
|
||||
Transcript t = Transcript.start("07-ten-problems.txt", "Ten interview problems: fast answer beside the brute-force answer");
|
||||
|
||||
int[] ins = {1, 3, 5, 6};
|
||||
for (int[] c : new int[][] {{5, 2}, {2, 1}, {7, 4}, {0, 0}}) {
|
||||
assertEquals(c[1], BinarySearch.insertPosition(ins, c[0]));
|
||||
assertEquals(c[1], BruteForce.searchInsert(ins, c[0]));
|
||||
t.line(row(1, "search insert position", Arrays.toString(ins) + " key=" + c[0],
|
||||
BinarySearch.insertPosition(ins, c[0]), BruteForce.searchInsert(ins, c[0])));
|
||||
}
|
||||
|
||||
int[] rng = {5, 7, 7, 8, 8, 10};
|
||||
for (int key : new int[] {8, 6}) {
|
||||
assertArrayEquals(BruteForce.searchRange(rng, key), InterviewProblems.searchRange(rng, key));
|
||||
t.line(row(2, "first and last position", Arrays.toString(rng) + " key=" + key,
|
||||
Arrays.toString(InterviewProblems.searchRange(rng, key)),
|
||||
Arrays.toString(BruteForce.searchRange(rng, key))));
|
||||
}
|
||||
|
||||
int[] dups = {1, 2, 2, 2, 2, 2, 3};
|
||||
assertEquals(5, BinarySearch.count(dups, 2));
|
||||
t.line(row(3, "count occurrences", Arrays.toString(dups) + " key=2",
|
||||
BinarySearch.count(dups, 2), BruteForce.count(dups, 2)));
|
||||
|
||||
int[] rot = {4, 5, 6, 7, 0, 1, 2};
|
||||
for (int key : new int[] {0, 3}) {
|
||||
assertEquals(BruteForce.indexOf(rot, key), RotatedArray.search(rot, key));
|
||||
t.line(row(4, "search in rotated array", Arrays.toString(rot) + " key=" + key,
|
||||
RotatedArray.search(rot, key), BruteForce.indexOf(rot, key)));
|
||||
}
|
||||
|
||||
int[] rot2 = {3, 4, 5, 1, 2};
|
||||
assertEquals(3, RotatedArray.minIndex(rot2));
|
||||
t.line(row(5, "minimum of rotated array", Arrays.toString(rot2) + " (index of min)",
|
||||
RotatedArray.minIndex(rot2), BruteForce.minIndex(rot2)));
|
||||
|
||||
int[] peaks = {1, 2, 1, 3, 5, 6, 4};
|
||||
int p = InterviewProblems.findPeak(peaks);
|
||||
assertTrue(BruteForce.isPeak(peaks, p));
|
||||
t.line(row(6, "find a peak element", Arrays.toString(peaks) + " (any peak is valid)",
|
||||
p, "peaks at 1 and 5, " + p + " is a peak: " + BruteForce.isPeak(peaks, p)));
|
||||
|
||||
for (int x : new int[] {4, 8}) {
|
||||
assertEquals(BruteForce.sqrt(x), SearchOnAnswer.sqrt(x));
|
||||
t.line(row(7, "integer square root", "x=" + x, SearchOnAnswer.sqrt(x), BruteForce.sqrt(x)));
|
||||
}
|
||||
|
||||
int[] piles = {3, 6, 7, 11};
|
||||
assertEquals(4, SearchOnAnswer.minEatingSpeed(piles, 8));
|
||||
t.line(row(8, "koko eating bananas", Arrays.toString(piles) + " h=8",
|
||||
SearchOnAnswer.minEatingSpeed(piles, 8), BruteForce.minEatingSpeed(piles, 8)));
|
||||
|
||||
int[] w = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||
assertEquals(15, SearchOnAnswer.shipWithinDays(w, 5));
|
||||
t.line(row(9, "ship packages within D days", "weights 1..10 days=5",
|
||||
SearchOnAnswer.shipWithinDays(w, 5), BruteForce.shipWithinDays(w, 5)));
|
||||
|
||||
int[][] m = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
|
||||
for (int target : new int[] {3, 13}) {
|
||||
assertEquals(BruteForce.searchMatrix(m, target), InterviewProblems.searchMatrix(m, target));
|
||||
t.line(row(10, "search a 2D matrix", "3x4 matrix target=" + target,
|
||||
InterviewProblems.searchMatrix(m, target), BruteForce.searchMatrix(m, target)));
|
||||
}
|
||||
t.flush();
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.ankurm.interviewlab.binarysearch.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<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user