Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Arrays.binarySearch returns a negative number when a key is missing. How do you use that value to insert the key into a sorted array, and what goes wrong if the array is not sorted?

When the key is missing, Arrays.binarySearch returns -(insertionPoint) - 1, where the insertion point is the index at which the key would have to go to keep the array sorted, so we recover it with insertionPoint = -result - 1 and copy the array into a new one with a gap there, using System.arraycopy. If the array is not sorted, the result is undefined: no exception, just a wrong answer. With duplicates, any matching index may be returned, and when searching with a Comparator it must be the same one used to sort.

Why this question is asked

Binary search is the standard way to find a value in sorted data in logarithmic time, and Java's version packs extra information into its return value: when the key is missing, the negative number also says where the key belongs. Knowing how to decode it turns a lookup into an efficient way to keep an array sorted. Interviewers ask this to see whether we know the encoding, can write the insertion correctly, and understand the method's contract and the quiet failures when it is broken. In this answer, we will recap binary search, decode the negative result, write the insertion, and then look at unsorted arrays, duplicates and comparators.

1A Quick Recap of Binary Search

Binary search works on a sorted array. It compares the key with the middle element; if the key is smaller it continues in the left half, if larger in the right half, and it repeats until it finds the key or the range becomes empty. Each step halves the range, so an array of a million elements needs at most about 20 comparisons. The whole method rests on one assumption: the array is sorted by the same ordering the search uses. Everything the search concludes about the half it throws away comes from that assumption.

2Decoding the Negative Result

When the search ends without finding the key, the range has narrowed to the exact position where the key would fit. Java returns that position, the insertion point, encoded as -(insertionPoint) - 1. The extra minus one exists because the insertion point can be 0, and -0 is just 0, which would look like found at index 0. Subtracting one makes every not-found result strictly negative.

Java
int[] a = {10, 20, 30, 40};
Arrays.binarySearch(a, 30); // 2: found at index 2
Arrays.binarySearch(a, 25); // -3: insertion point 2, between 20 and 30
Arrays.binarySearch(a, 5); // -1: insertion point 0, before everything
Arrays.binarySearch(a, 50); // -5: insertion point 4, which is a.length, after everything
int r = Arrays.binarySearch(a, 25);
int insertionPoint = -r - 1; // 2 (the same as ~r, the bitwise complement)
Decoding results for {10, 20, 30, 40}
KeyResultMeaning
302Found at index 2
25-3Missing; insert at -(-3) - 1 = 2
5-1Missing; insert at 0
50-5Missing; insert at 4, the end

So the rule is: a result of 0 or more is the index of the key, and a negative result r means not found, with the key belonging at -r - 1. Notice that the insertion point can equal a.length, when the key is larger than every element, so code that uses it as an index must allow for that.

3Inserting the Key Into a Sorted Array

Arrays have a fixed length, so inserting means creating a new array one element longer, copying the elements before the insertion point, placing the key, and copying the rest one position to the right. System.arraycopy does the copying efficiently.

Java
static int[] insertSorted(int[] a, int key) {
int r = Arrays.binarySearch(a, key);
int pos = r >= 0 ? r : -r - 1; // insert next to an equal key, or at the insertion point
int[] out = new int[a.length + 1];
System.arraycopy(a, 0, out, 0, pos); // elements before pos
out[pos] = key;
System.arraycopy(a, pos, out, pos + 1, a.length - pos); // the rest, shifted right by one
return out;
}
insertSorted(new int[] {10, 20, 30, 40}, 25); // [10, 20, 25, 30, 40]
insertSorted(new int[] {10, 20, 30, 40}, 50); // [10, 20, 30, 40, 50]
insertSorted(new int[0], 7); // [7]
Step throughInsert a key while keeping the array sorted
  1. r = binarySearch(a, key)O(log n)
  2. Is r negative?
    Yespos = -r - 1, the insertion pointNopos = r, next to the equal key
  3. Copy a[0..pos) into a new arraySystem.arraycopy
  4. Put key at pos, copy the rest to pos + 1O(n) in total

4 steps in order. Play them, or step through them one at a time.

Finding the position takes O(log n), but the copy takes O(n), so each insertion is linear. That is fine for occasional inserts. If we insert many keys, a sorted collection is the better structure: a TreeSet or TreeMap keeps elements ordered with O(log n) inserts, or we collect all keys first and sort once. For a growing list we can also use ArrayList.add(pos, key) with the same insertion point, which shifts elements in the same way but manages capacity for us.

4What Happens If the Array Is Not Sorted

The search never checks that the array is sorted, because checking would take O(n) and defeat the purpose. If the array is not sorted, the method still runs and returns a number, but the number means nothing. It may find the key by chance, or report it missing although it is there.

Java
int[] unsorted = {30, 10, 40, 20};
Arrays.binarySearch(unsorted, 10); // 1: correct, by luck
Arrays.binarySearch(unsorted, 30); // -3: says 30 is missing, yet it is at index 0

The second search looks at index 1, sees 10, decides 30 must be to the right, then sees 40 and decides it must be to the left, and gives up. There is no exception, which makes the bug quiet. The defence is to make sortedness part of the data's contract: sort in the same place we build the array, document it, and in tests assert it.

5Duplicates and Comparators

If the array contains several equal keys, the documentation only promises that one of them is found, not which one. In {1, 2, 2, 2, 3}, searching for 2 returns 2, the middle copy, because that is where the first comparison landed. When we need the first or last occurrence, we write a lower-bound search that keeps going left after a match, or step left from the result while the previous element is equal.

Java
String[] words = {"Banana", "apple", "cherry"};
Arrays.sort(words, String.CASE_INSENSITIVE_ORDER); // [apple, Banana, cherry]
Arrays.binarySearch(words, "apple"); // -3: natural order disagrees
Arrays.binarySearch(words, "apple", String.CASE_INSENSITIVE_ORDER); // 0: same comparator as the sort

The comparator rule follows from the same assumption as before. The array is sorted case-insensitively, but the first search compares with natural String order, in which upper-case letters come before lower-case ones, so its decisions about which half to discard are wrong. Whenever we sort with a Comparator, we must pass the very same Comparator to binarySearch, and Collections.binarySearch on a List has the same rule.

6Follow-up questions

Why does Java return -(insertionPoint) - 1 instead of simply -insertionPoint?

Because the insertion point can be 0. If the method returned -insertionPoint, a key smaller than every element would produce -0, which is 0, and that is indistinguishable from finding the key at index 0. Subtracting one shifts all not-found results to -1 and below, so the sign alone tells us whether the key was found. The decoding is -r - 1, which is the same as the bitwise complement ~r.

What was the famous overflow bug in binary search?

Many implementations computed the middle index as (low + high) / 2. For arrays with more than about a billion elements, low + high can exceed Integer.MAX_VALUE and wrap around to a negative number, causing an exception or wrong results. The JDK's own implementation had this bug until it was fixed in JDK 6, and it now uses (low + high) >>> 1, an unsigned shift that gives the correct middle even when the sum overflows. It is a good example of how a textbook algorithm can hide a bug for years.

Can we binary search a List?

Yes, with Collections.binarySearch(list, key) or the overload with a Comparator, under the same rules and the same return encoding. For a list with fast random access, such as ArrayList, it runs in O(log n). For a LinkedList it still works, using an iterator-based search, but reaching the middle element costs O(n), so a sorted LinkedList is rarely the right structure for searching.

7Conclusion

In this answer, we saw that Arrays.binarySearch returns -(insertionPoint) - 1 for a missing key, with the minus one keeping the result negative when the insertion point is 0, so we decode it as -r - 1 and insert the key by copying into a longer array with System.arraycopy, an O(n) step that suggests a TreeSet or a single sort when inserts are frequent. On an unsorted array the result is undefined and no error is raised, with duplicates any matching index may come back, and the comparator used to search must be the one used to sort.

What to say in the interviewAbout 100 seconds aloud

Open with

When the key isn't found, binarySearch returns minus the insertion point minus one, where the insertion point is the index where the key would go to keep the array sorted.

Then, if they want more

The minus one is there because the insertion point can be zero, and minus zero would look like found at index zero. So I decode it as insertionPoint equals minus result minus one, which is also the bitwise complement.

For example, in 10, 20, 30, 40, searching 25 returns minus 3, so it belongs at index 2, and searching 50 returns minus 5, which is the array length, so it goes at the end.

To insert, I create a new array one longer, System.arraycopy the elements before that position, put the key in, and arraycopy the rest shifted by one. Finding the spot is log n, but the copy is linear, so for many insertions I'd use a TreeSet or TreeMap, or collect everything and sort once.

If the array isn't sorted, the result is undefined. It doesn't throw; it just gives a wrong answer, for example reporting a key missing that's actually there, because it discards the wrong half. With duplicates, any of the matching indexes may be returned, so if I need the first one I write a lower-bound search.

And if the array was sorted with a Comparator, I must search with that same Comparator; searching a case-insensitively sorted array with natural order can miss elements.

About this answer

Last updated
12 November 2026
Versions it names
Java 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 "Arrays.binarySearch returns a negative number when a key is missing. How do you use that...": https://scrivio-interview-library.netlify.app/java/arrays/e88aa606a1/