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:
@@ -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
|
||||
Reference in New Issue
Block a user