Skip to main content

Binary Search in Java: Iterative, Recursive, Lower/Upper Bound and 10 Interview Problems

Binary search in Java explained from scratch: the iterative and recursive loop, the (lo + hi) / 2 overflow bug, lower and upper bound, rotated arrays, searching for the answer and 10 interview problems, with every figure taken from a real run.

You have a sorted list of a million numbers and you need to know whether 837,291 is in it. Reading them one by one can take a million looks. Binary search needs at most twenty — counted by the companion code, not estimated. That is the whole trick, and it is also the reason this one algorithm turns up in almost every Java interview: it is small enough to write on a whiteboard, and subtle enough that most hand-written versions have a bug. This page starts with the smallest version that works, then follows the bugs, the variants (first/last occurrence, rotated arrays, “search the answer”) and ten interview problems built from them. It replaces the 2015 post at this URL; the original console program is still here, in the second section.
Verified against: JDK Temurin 25.0.5.1+2 (LTS), JUnit 6.1.3 (latest GA on Maven Central), Maven 3.9.11. Every number and console line on this page comes from a file in the binary-search module; one command (./scripts/run-all.sh) regenerates all 14 transcripts, and the tests assert the same numbers they print.

Why look at the middle of a sorted list?

Open a paper phone book in the middle. If the name you want comes later in the alphabet, you never look at the first half again; if it comes earlier, you never look at the second. One look removes half of everything that is left. Binary search is that idea written as a loop: a divide-and-conquer algorithm that finds the position of a target value in a sorted array, instead of checking each element one by one like a linear search.
  1. Start with the middle element of the array.
  2. If the middle element is the target, return its index.
  3. If the target is smaller, repeat the search on the left half.
  4. If the target is greater, repeat the search on the right half.
  5. Continue until the element is found or the sub-array size becomes zero.
Sorted is the whole deal. Binary search never checks that the array is sorted, and on unsorted input it does not fail loudly — it quietly returns the wrong answer. A later section reproduces that.
Here it is on sixteen sorted values, searching for 26. Each row is one look; the blue cells are the range that is still possible, the amber outline is the middle cell being examined, and the grey cells have already been ruled out.
0123456789101112131415look 12468101214161820222426283032look 22468101214161820222426283032look 32468101214161820222426283032look 42468101214161820222426283032Key 26. Look 1: 26 > 16, discard the left half. Look 2: 26 > 24, discard again.Look 3: 26 < 28, keep only index 12. Look 4: found. Blue = still possible, amber outline = the middle looked at.
Four looks and the search ends at index 12, where a linear scan would have needed 13 (transcript 13). The point of the picture is the shrinking blue range: 16, 8, 4, 1. Because the range halves every time, doubling the array adds one look, not double the work.
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
Going deeper: where the “log” comes from and how many looks are really needed A range of n candidates can be halved about log2(n) times before one is left, so the worst case is floor(log2 n) + 1 looks for this loop. That formula was checked exhaustively — every present key, every gap between keys and both ends — for n up to 1,000,000, and sampled for a billion elements using a memory-free sequence (see the overflow section). Counted, not timed: wall-clock numbers depend on the machine, counts do not. Source: 09-operation-counts.txt, produced by ComplexityTest.java.
            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
  • A linear scan on an absent key looks at all n elements, which is the column on the left.
  • Sorting an array just to search it once costs more than scanning it once; binary search pays off when you search the same sorted data repeatedly. See the sorting basics post for the sorting side.
  • More array fundamentals: array programs for interviews.

The smallest version that works

Two variables, lo and hi, mark the part of the array where the key could still be. The loop keeps one promise (computer scientists call it an invariant): if the key is in the array at all, it is between lo and hi, inclusive. Every step looks at the middle, then moves lo or hi past it. When lo passes hi the range is empty, the promise says the key cannot exist, and the method returns -1. The method is iterative in BinarySearch.java:
    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;
    }
Running it on [10, 20, 30, 40, 45] for 40, 10 and 25 — the same three searches the 2015 post walked through — with a trace copy of the loop that prints every step (DryRuns.java; the test asserts the trace returns what the real method returns):
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
Captured output: 01-dry-run-iterative.txt Reading the traces: searching for 40, the first middle is index 2 (value 30); 40 is bigger so lo becomes 3, and the next middle is index 3, which is 40. Searching for 10 does the mirror image on the left. Searching for 25, which is not in the array, the range shrinks 5, 2, 1, 0 elements until lo is greater than hi, and the method returns -1. The “position” the old program printed counts from 1 (index + 1); the method itself returns the 0-based index.
One line differs from what you may have seen. The middle is lo + (hi - lo) / 2, not (lo + hi) / 2. They are equal on paper and not equal on a computer; the overflow section below is about exactly that.
The original 2015 console program, kept as it was (with one fix) The first version of this article was a console program: type how many numbers, type them in increasing order, then search as many times as you like. It is still in the repository as InteractiveDemo.java, with the midpoint fixed and the loop moved into a method so a test can drive it. Run it yourself with java InteractiveDemo.java.
    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"));
    }
The method it calls is the same algorithm as above, under its original 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;
    }
Source: InteractiveDemo.java
  1. The program first takes the size of the array and the elements in increasing order.
  2. It then asks for a number to search and calls performBinarySearch.
  3. That method calculates the mid index, compares it with the key, and adjusts low or high to narrow the search space; it returns the index or -1.
  4. The user can repeat this until they answer something other than y.
The sample session from the old post, reproduced by InteractiveDemoTest.java, which asserts it matches the 2015 text character for character. Input is scripted, so the program echoes each value after its prompt the way a terminal would show what you typed:
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
Captured output: 11-interactive-session.txt

Loop or recursion: which one should you write?

Either. Recursion expresses “search the left half” or “search the right half” literally: each call owns a range and hands a smaller one to the next call. The method is recursive in BinarySearch.java:
    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);
    }
The two versions gave identical answers on all 2,003 keys of a 1,000-element array (every present key, every gap, both ends). What differs is the cost of the calls: each recursive step is one more stack frame, counted here by DryRuns.recursiveDepth (transcript 02):
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)
Twenty-one frames for a million elements is nothing to worry about. The loop is still the better default in real code: no frames, and the invariant above is easier to check by eye when the state is two variables rather than a call stack.
Going deeper: recursion, frames and what “tail call” does and does not mean in Java The recursive call is the last thing the method does (a tail call), which some languages turn into a jump. Java the language does not promise that, so on this page a recursive call is counted as a frame, as the transcript does. The frame count is the number of probes plus one base-case call for the empty range, which is why n = 10 shows 5 frames while the loop looks at 4 elements.

The bug that sat in the JDK for years: (lo + hi) / 2

A Java int tops out at 2,147,483,647. Adding two array indexes that are each below that can still land above it, and when that happens Java does not complain: the sum wraps around to a negative number. Half of a negative number is a negative index, and the next array read throws.
02,147,483,647Integer.MAX_VALUElo = 1,000,000,000hi = 1,999,999,999lo + hi = 2,999,999,999 is past the end of the lineit wraps to -1,294,967,297; halved, mid = -647,483,648, a negative array indexBoth markers are valid indexes. Their sum is not a valid int. lo + (hi – lo) / 2 stays on the line: 1,499,999,999.
The picture is the number line of ints. The two markers are perfectly legal indexes in a two-billion-element array, but their sum lies off the end of the line, so it wraps to -1,294,967,297. A real int[] of two billion elements needs about 8 GB, so Overflow.java searches a memory-free sorted sequence (element i is just i) whose get throws the same exception type a real array would. That is a stand-in, and the transcript says so in its header:
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
Captured output: 03-overflow-mid.txt The first step is fine (the sum is 1,999,999,999); the second step overflows and the search dies with an ArrayIndexOutOfBoundsException on a negative index, even though the key is sitting at the very end. This is not a theoretical worry. Joshua Bloch wrote it up in June 2006 on the Google Research blog: the same line had been in Bentley’s Programming Pearls and in java.util.Arrays for years, and it only shows up at roughly a billion elements or more (his post). Here is what today’s JDK does, read straight out of this JDK’s own lib/src.zip (transcript 12):
 1703          while (low <= high) {
 1704              int mid = (low + high) >>> 1;
 1705              int midVal = a[mid];
Two safe spellings. lo + (hi - lo) / 2 never overflows because hi - lo is at most the array length. (lo + hi) >>> 1 (what the JDK uses) lets the sum wrap but reads it as an unsigned number before halving, which is still correct. Either is fine; (lo + hi) / 2 is not.
Going deeper: why both fixes work, and the code that proves it For non-negative lo <= hi, hi - lo is between 0 and hi, so it cannot overflow, and adding it to lo gives a value no larger than hi. For the shift: two non-negative ints sum to less than 232, so the sum fits in 32 unsigned bits; >>> halves those bits as an unsigned value, and the result is below 231. The broken and fixed searches side by side, in Overflow.java:
    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;
    }
    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;
    }
Source: Overflow.java
  • The test that prints transcript 03 also asserts that both fixes find the last element: OverflowTest.java.
  • Java arrays are indexed by int, so no array is bigger than 231-1 elements; the problem is the sum of two valid indexes, not an index itself.

When the key appears many times: lower bound and upper bound

Plain binary search returns an index of the key, not a particular one. On [1, 2, 2, 2, 2, 2, 3] it returns index 3 for the key 2, while the first 2 is at index 1 and the last at index 5 (transcript 10). The Javadoc of Arrays.binarySearch says the same thing in its own words: with several equal elements there is no guarantee which one is found.
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
The fix is to ask a different question. Instead of “where is the key?”, ask “where is the first element that is not smaller than the key?” That index is the lower bound; the first element greater than the key is the upper bound. Everything between them equals the key, so first position, last position and count all fall out of two searches. Note the loop below: the range is half-open — hi starts at a.length, one past the end, because “no element is big enough” is a legitimate answer. The method is lowerBound in BinarySearch.java:
    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;
    }
01122232425263758598lowerBound(2) = 1upperBound(2) = 6count = 6 – 1 = 5lowerBound = first index with a[i] >= key; upperBound = first index with a[i] > key. Cells between them equal the key.
On [1, 2, 2, 2, 2, 2, 3, 5, 5, 8], lowerBound(2) is 1 and upperBound(2) is 6; the count is simply 6 − 1 = 5. A key that is absent gets the same index from both, which is exactly where it would have to be inserted. The table is transcript 04, checked against a brute-force scan by BoundsTest.java; the last column is what the JDK’s own Arrays.binarySearch returned for the same key.
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
Java has no lowerBound. Listing the public methods of java.util.Arrays, Collections and List on this JDK finds binarySearch overloads and nothing with “bound” in its name, so for first/last occurrence you write this yourself (transcript 14, a reflection check run by JdkSourceTest.java).
Going deeper: the trace, the helpers built on it, and the negative return value Here is lowerBound for the key 2, step by step. Note how hi = mid (not mid - 1) keeps a possible answer inside the range:
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
Captured output: 04-lower-upper-bound.txt The helpers are one line each on top of the two bounds (BinarySearch.java):
    public static int firstOccurrence(int[] a, int key) {
        int i = lowerBound(a, key);
        return i < a.length && a[i] == key ? i : -1;
    }
    public static int count(int[] a, int key) {
        return upperBound(a, key) - lowerBound(a, key);
    }
Source: BinarySearch.java The last column of the table also shows the JDK’s convention for “not found”: Arrays.binarySearch returns -(insertion point) - 1, so key 4 gave -8 (insertion point 7) and key 9 gave -11. Code that tests == -1 for “not found” is wrong for every key except the one that belongs at index 0; code that tests < 0 is right.
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
Captured output: 10-pitfalls.txt

When the array has been rotated

Take a sorted array and rotate it, so that [0, 1, 2, 4, 5, 6, 7] becomes [4, 5, 6, 7, 0, 1, 2]. The whole array is no longer sorted, so the plain algorithm breaks. But look at any middle element: one side of it is still a sorted run. That is enough, because you can check whether the key falls inside the sorted side and, if not, throw that side away.
04152637405162sorted run 4..7sorted run 0..2mid = index 3 (value 7). The left side 4..7 is sorted. Does it hold the key 0? No, so discard it.Whichever side of the middle you look at, at least one of the two sides is a sorted run.
Here the middle is index 3 (value 7); the run 4..7 on its left is sorted. If the key is 0, it is not inside 4..7, so discard the left half. The method for distinct values is search in RotatedArray.java:
    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;
    }
Both searches below, traced (transcript 05). The test also checks every rotation of every distinct array of length 1 to 12 against every key — 2,184 searches, no disagreements (RotatedTest.java):
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
Duplicates quietly break the speed. With many equal values, comparing the middle with the end proves nothing, and the only safe move is to shrink the range by one element. On [1, 0, 1, 1, …, 1] that turned a 12-step search into a 4,094-step one at n = 4,096. Still correct, no longer logarithmic.
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
Captured output: 05-rotated-array.txt
Going deeper: finding the rotation point, and why you compare with hi, not lo The minimum of a rotated array is where the drop happens. Compare the middle with the last element of the range: if the middle is bigger, the drop is to its right; otherwise the middle could itself be the minimum, so keep it. Comparing with the first element is ambiguous when the range happens not to contain the drop. The method is minIndex, and the version tolerating duplicates is minWithDuplicates, both in RotatedArray.java:
    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;
    }
    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};
    }
Source: RotatedArray.java
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
Captured output: 05-rotated-array.txt

Binary search with no array: searching for the answer

The same loop works on anything that flips from “no” to “yes” exactly once. Koko loves bananas: there are piles of 3, 6, 7 and 11, the guards return in 8 hours, and each hour she eats from one pile at some speed k bananas per hour. What is the slowest speed that finishes in time? There is no sorted array here, but there is a sorted question: if speed k is fast enough, so is every larger speed.
speed kenough?hours1no272no153no104yes85yes86yes67yes58yes59yes510yes511yes4first yes = 4, the answerPiles 3, 6, 7, 11 and 8 hours allowed. The row of answers is no, no, no, yes, yes, … so one boundary search finds the switch.
Speeds 1, 2 and 3 are too slow (27, 15 and 10 hours); from 4 upwards the 8-hour limit is met, so the answer is the first “yes”. That is the lower-bound loop again, over candidate speeds instead of array indexes. The reusable piece is firstTrue in SearchOnAnswer.java:
    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;
    }
and Koko’s problem is that loop plus a way to answer “is speed k enough?”:
    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);
    }
Source: SearchOnAnswer.java The transcript counts how many times the yes/no question was asked. The integer square root at the top is the same pattern with the question “is m × m bigger than x?” (transcript 06, from SearchOnAnswerTest.java):
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
For the square root of 2,147,483,647 that is 31 questions instead of up to 2,147,483,648 candidates.
Three things must hold. The yes/no answer must be monotone (once yes, always yes for larger candidates); the range you search must contain the answer, with the upper end a guaranteed yes; and checking one candidate must be cheap relative to trying them all.
Going deeper: ship packages, square roots and why the code uses long Ship packages within D days is the same shape: the candidate is a ship capacity, the answer lies between the heaviest single package and the total weight, and the question is “can the packages be loaded, in order, within D days at this capacity?”. The square root uses long because m * m overflows an int long before m reaches 231; with long the answer for Integer.MAX_VALUE comes out as 46,340. Both are in SearchOnAnswer.java:
    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);
    }
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
Captured output: 06-search-on-answer.txt
    public static int sqrt(int x, LongPredicate probe) {
        long firstTooBig = firstTrue(0, (long) x + 1, probe);
        return (int) (firstTooBig - 1);
    }
Source: SearchOnAnswer.java

Ten interview problems, one pattern each

Almost every binary-search interview question is one of the three shapes above in disguise. The table maps ten common problems to the code; each row is a method in the repository.
#ProblemPatternMethod
1Search insert positionlower boundBinarySearch.insertPosition
2First and last position of a valuelower + upper boundInterviewProblems.searchRange
3Count occurrencesupper − lower boundBinarySearch.count
4Search in a rotated arrayone half is sortedRotatedArray.search
5Minimum of a rotated arraycompare with the endRotatedArray.minIndex
6Find a peak elementfollow the slopeInterviewProblems.findPeak
7Integer square rootsearch on the answerSearchOnAnswer.sqrt
8Koko eating bananassearch on the answerSearchOnAnswer.minEatingSpeed
9Ship packages within D dayssearch on the answerSearchOnAnswer.shipWithinDays
10Search a 2D matrixflatten the indexInterviewProblems.searchMatrix
Each solution is checked two ways. First, one hand-picked example against a slow, obviously-correct brute force written without sharing any helper with the fast code (transcript 07):
 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
Second, seeded random inputs: the fast version and the brute force must agree on every one (transcript 08, RandomAgreementTest.java). That is 34,000 comparisons, and the test fails on the first disagreement:
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
Going deeper: the ten problems, what to say in the interview and where each one bites 1. Search insert position. It is lowerBound under another name: the answer for a missing key is where it would be inserted, and a key bigger than everything returns a.length, which is why the loop’s range is half-open. On [1, 3, 5, 6] the keys 5, 2, 7 and 0 give 2, 1, 4 and 0. 2. First and last position. Two bound searches, then check the element actually equals the key; a missing key gives [-1, -1]. On [5, 7, 7, 8, 8, 10] the key 8 gives [3, 4]. Two logarithmic searches beat one search plus a walk outwards when the key is repeated a million times. 3. Count occurrences. upperBound - lowerBound, with no loop over the matches; on [1, 2, 2, 2, 2, 2, 3] the key 2 gives 5. 4. Search in a rotated array. Decide which half is sorted by comparing a[lo] with a[mid], check whether the key lies inside that half, and otherwise go the other way. Distinct values only; see the duplicates warning above. 5. Minimum of a rotated array. The drop is where the minimum lives. Compare the middle with a[hi]. On [3, 4, 5, 1, 2] the answer is index 3. 6. Find a peak element. A peak is strictly greater than both neighbours (outside the array counts as minus infinity); adjacent values must differ. If a[mid] < a[mid + 1] the slope rises, so a peak exists to the right; otherwise one exists at mid or to its left. Any peak is accepted: on [1, 2, 1, 3, 5, 6, 4] there are two, at indexes 1 and 5, and the search returned 5. Method findPeak in InterviewProblems.java:
    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;
    }
7. Integer square root. Search on the answer with the question “is m × m bigger than x?” and subtract one from the first yes. Use long for the product. 8. Koko eating bananas. Candidates are speeds 1 to the largest pile; the question sums ceil(pile / speed) over the piles and compares with h. 9. Ship packages within D days. Candidates run from the heaviest package to the sum of all weights; the question simulates loading in order and counts days. On weights 1 to 10 with 5 days the answer is 15: at capacity 14 it takes 6 days. 10. Search a 2D matrix. When each row is sorted and each row starts above the end of the previous one, the matrix is one sorted array in disguise; index i lives at [i / cols][i % cols]. Method searchMatrix in InterviewProblems.java:
    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;
    }

What goes wrong, and what the symptom looks like

Binary search is a few lines long and most of its bugs are one character. These are the ones reproduced by PitfallsTest.java, with the symptom each one produces (transcript 10):
  • The overflowing midpoint: a negative index and an ArrayIndexOutOfBoundsException, but only on huge arrays — the kind of bug tests never find (see above).
  • hi = a.length with an inclusive loop: an ArrayIndexOutOfBoundsException when the key is bigger than everything.
  • lo = mid instead of lo = mid + 1: an infinite loop that appears only when the range shrinks to the last one or two elements.
  • Unsorted input: the wrong answer, silently.
  • Duplicates: “an” index, not “the first” or “the last” one.
  • Comparing the JDK’s result with -1: misses every negative result except one.
  • Rotated arrays with duplicates: correct but linear (see above).
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
The infinite loop is the nastiest because nothing ever fails: the demo has to cap the iterations at six to stop. Look at the log — low, high and mid are identical on every line. And the unsorted case returns -1 for a key that is plainly in the array.
3. unsorted input [5, 1, 2, 9, 3], key 3
   binary search returns -1, a linear scan returns 4
Captured output: 10-pitfalls.txt
Going deeper: the two wrong versions, line by line Both are one edit away from the correct loop, which is why they survive code review. They live in Pitfalls.java, next to the corrected loop in BinarySearch.java:
    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;
    }
    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;
    }
Source: Pitfalls.java

Should you write binary search yourself?

Usually not. For “is this value in my sorted array or list”, use Arrays.binarySearch or Collections.binarySearch: they are tested, they use the unsigned-shift midpoint, and you now know to test their result with < 0. Write your own when the JDK has nothing to offer — first or last occurrence, counting, rotated arrays, and above all searching an answer rather than an array — and in interviews, where the loop itself is the question. If you will search the data only once, scanning it is cheaper than sorting it first.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.