Quick revision
The short answer
We search a half-open range with lo = 0 and hi = a.length: while lo < hi, take mid = lo + (hi - lo) / 2, move lo to mid + 1 if a[mid] < target, otherwise move hi to mid, and return lo, which is the first index whose element is >= target, or a.length if there is none. The half-open range and a clear invariant prevent off-by-one errors, and computing mid as lo + (hi - lo) / 2 or (lo + hi) >>> 1 prevents the integer overflow that sat in the JDK's own binarySearch until 2006. It runs in O(log n) time and O(1) space on an array sorted in the same order.
What to remember
In this answer, we wrote a lower-bound binary search on a half-open range: lo = 0, hi = a.length, loop while lo < hi, move lo past mid when a[mid] is smaller than the target and move hi to mid otherwise, and return lo. An invariant explains why it never skips the answer or loops forever, lo + (hi - lo) / 2 or (lo + hi) >>> 1 avoids the overflow that was in the JDK until 2006, Arrays.binarySearch differs by returning -(insertionPoint) - 1 and any matching index for duplicates, and the upper bound gives the last occurrence.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We search a half-open range with lo = 0 and hi = a.length: while lo < hi, take mid = lo + (hi - lo) / 2, move lo to mid + 1 if a[mid] < target, otherwise move hi to mid, and return lo, which is the first index whose element is >= target, or a.length if there is none. The half-open range and a clear invariant prevent off-by-one errors, and computing mid as lo + (hi - lo) / 2 or (lo + hi) >>> 1 prevents the integer overflow that sat in the JDK's own binarySearch until 2006. It runs in O(log n) time and O(1) space on an array sorted in the same order.
Background to this question
Binary search is famous for being simple to describe and hard to get exactly right. Off-by-one mistakes give infinite loops or skip the answer, and the classic midpoint calculation overflows on very large arrays. The lower-bound variant in this question is the most useful one in practice: it finds where a value is or where it would go, which is what we need for range queries, inserting into sorted data, or finding the first event after a timestamp. In this answer, we will recap what lower bound means, write the code, trace it on an example, see why the invariant prevents off-by-one bugs, look at the overflow bug, compare with Arrays.binarySearch, and finish with the complexity and the last-occurrence variant.
1A Quick Recap of Lower Bound
Given a sorted array and a target, the lower bound is the index of the first element that is greater than or equal to the target. If the target is present, it is the index of its first occurrence. If it is absent, it is the position where the target would be inserted to keep the array sorted. If every element is smaller than the target, the answer is a.length, one past the end.
For a = {1, 3, 3, 5, 8, 9}: the lower bound of 3 is 1, the first of the two 3s; the lower bound of 4 is 3, where 5 sits; the lower bound of 0 is 0; and the lower bound of 10 is 6, which is a.length.
2The Code
Here is the full method, followed by those four calls.
Notice the asymmetry between the two branches. When a[mid] is smaller than the target, mid cannot be the answer, so we exclude it with mid + 1. When a[mid] is greater than or equal to the target, mid might be the answer, so we keep it by setting hi = mid rather than mid - 1. That asymmetry is the whole trick.
3Tracing It Step by Step
Let us follow lowerBound(a, 3) on a = {1, 3, 3, 5, 8, 9} to see the range shrink.
| lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|
| 0 | 6 | 3 | 5 | 5 >= 3, so hi = 3 |
| 0 | 3 | 1 | 3 | 3 >= 3, so hi = 1 |
| 0 | 1 | 0 | 1 | 1 < 3, so lo = 1 |
| 1 | 1 | - | - | lo == hi, return 1 |
Even though the second step landed exactly on a 3, the search did not stop. It kept going left, because there might be an earlier 3, which is what makes this a lower bound and not just 'any index of 3'.
4Why This Avoids Off-by-One Bugs
The reliable way to write binary search is to state an invariant, a fact that is true before and after every loop iteration, and check that each line keeps it. Here the invariant is: every element before lo is smaller than the target, and every element from hi onwards is greater than or equal to it. At the start, lo = 0 and hi = a.length, so both parts are empty and the invariant holds trivially.
Each branch keeps it. If a[mid] < target, then, since the array is sorted, everything up to and including mid is smaller, so moving lo to mid + 1 is safe. If a[mid] >= target, everything from mid onwards is at least the target, so moving hi to mid is safe. The loop also always makes progress: mid is at least lo and strictly less than hi, so either lo grows or hi shrinks. When lo == hi, the invariant says everything before lo is smaller and everything from lo onwards is at least the target, so lo is the answer.
Most binary search bugs come from mixing styles: a closed range [lo, hi] with hi = a.length - 1 combined with hi = mid, or a loop condition of lo <= hi with a half-open range. Either can loop forever or skip the answer. Picking the half-open style and sticking to it removes that whole class of errors.
5The Overflow Bug That Lived in the JDK
The textbook midpoint, (lo + hi) / 2, has a hidden flaw. lo and hi are ints, and their sum can exceed Integer.MAX_VALUE, 2,147,483,647, when the array has more than about a billion elements.
A negative mid throws ArrayIndexOutOfBoundsException. This exact bug was in java.util.Arrays.binarySearch, and in many textbook implementations, for years until it was reported and fixed in 2006, once arrays of that size became practical. lo + (hi - lo) / 2 never overflows, because hi - lo fits in an int when both are valid indexes. (lo + hi) >>> 1 works too, because the unsigned shift interprets the overflowed 32-bit sum correctly; the JDK uses that form.
6How Arrays.binarySearch Differs
The JDK's Arrays.binarySearch looks for an exact match. If it finds the key, it returns its index; if not, it returns -(insertionPoint) - 1, a negative number that encodes where the key would go. The extra -1 is needed so that 'not found, insert at 0' is distinguishable from 'found at 0'. And with duplicates, it makes no promise about which matching index it returns.
So if we need the first occurrence or a guaranteed insertion point with duplicates, Arrays.binarySearch is not enough, and our lowerBound is the right tool. For sorted collections rather than arrays, TreeMap.ceilingKey and TreeSet.ceiling give lower-bound behaviour directly.
7Complexity, Preconditions and the Last Occurrence
Each iteration halves the range, so the loop runs at most about log2(n) + 1 times: around 31 iterations for two billion elements. That is O(log n) time and O(1) extra space. The precondition is that the array is sorted in the same order the search uses. If the array is sorted descending, or with a different comparator, the result is meaningless, and Java does not check this for us.
To find the last occurrence, we search for the upper bound, the first element strictly greater than the target, and step back one.
8Follow-up questions
How would you find the last occurrence instead?
Compute the upper bound, the first index whose element is strictly greater than the target, using the same loop with a[mid] <= target in place of a[mid] < target. The last occurrence is that index minus one, provided it is at least 0 and the element there equals the target; otherwise the target is absent. Upper bound minus lower bound also gives the number of occurrences.
Why use a half-open range instead of a closed one?
Because it represents an empty range naturally as lo == hi, lets hi start at a.length without special cases, and makes the answer 'one past the end' expressible when no element qualifies. It also matches Java's own conventions, such as List.subList(from, to) and Arrays.copyOfRange, so it is the style least likely to cause confusion.
Does this work for doubles or objects?
Yes, with the comparison replaced. For doubles, Double.compare(a[mid], target) < 0 handles NaN and -0.0 consistently with Arrays.sort. For objects, use comparator.compare(a[mid], target) < 0 with the same comparator that sorted the array.
9Conclusion
In this answer, we wrote a lower-bound binary search on a half-open range: lo = 0, hi = a.length, loop while lo < hi, move lo past mid when a[mid] is smaller than the target and move hi to mid otherwise, and return lo. An invariant explains why it never skips the answer or loops forever, lo + (hi - lo) / 2 or (lo + hi) >>> 1 avoids the overflow that was in the JDK until 2006, Arrays.binarySearch differs by returning -(insertionPoint) - 1 and any matching index for duplicates, and the upper bound gives the last occurrence.
Open with
I use a half-open range: lo starts at zero and hi at a.length, and the loop runs while lo is less than hi. I compute mid as lo plus hi minus lo over two, or lo plus hi unsigned-shifted right by one, never lo plus hi over two, because that sum can overflow for arrays over about a billion elements.
Then, if they want more
That was a real bug in the JDK's binarySearch until 2006. Then, if a[mid] is less than the target, the answer must be after mid, so lo becomes mid plus one. Otherwise a[mid] is greater than or equal to the target and could be the answer, so hi becomes mid, not mid minus one.
When the loop ends, lo equals hi and that's the first index with an element at least the target, or a.length if there isn't one. The way I avoid off-by-one bugs is by keeping an invariant: everything before lo is smaller than the target, and everything from hi on is at least the target.
Each branch keeps it true and the range shrinks every time, so the loop terminates with the right answer. It's O(log n) time and constant space, and the array must be sorted in the same order.
I'd also mention that Arrays.binarySearch is different: it returns minus insertion point minus one when the key is missing, and with duplicates it can return any matching index, for example 2 instead of 1 in this array. For the last occurrence, I'd use the same loop with less-than-or-equal to get the upper bound and subtract one.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a binary search that returns the index of the first element >= target in a sorted...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/2559460877/