Single Element in a Sorted Array

Find the one number without a twin in a sorted array of pairs, by checking where the pairs start.

Given a sorted array of integers nums in which every number appears exactly twice except one, return the number that appears only once. The search must take O(log n) time, where n is the length of the array, and use O(1) extra space: a fixed amount of memory however long the array is.

Example 1
Input: nums = [1, 1, 2, 3, 3, 4, 4, 8, 8]
Output: 2
Example 2
Input: nums = [3, 3, 7, 7, 10, 11, 11]
Output: 10
Solution

The Idea

Think of a shelf of shoes put out in pairs, each pair side by side, with one shoe that has lost its partner. Example 1 is that shelf in numbers: 1 and 1, then 2 alone, then 3 and 3, 4 and 4, 8 and 8. Because the array is sorted, the two copies of a number always sit next to each other.

Reading the shelf from the left, two numbers at a time, finds the lonely 2 quickly here. But on a long array with the single number near the end, that reads almost everything. So the real question is: can we look at one spot in the middle and tell whether the single number is to its left or to its right?

The spots have numbers. Each position in the array is called an index, counted from 0, so in Example 1 index 0 holds 1 and index 2 holds 2. An index is even if it divides by 2 (0, 2, 4, ...) and odd if it does not (1, 3, 5, ...). Look at the picture below.

The array 1, 1, 2, 3, 3, 4, 4, 8, 8 with indexes 0 to 8. Before the 2, the pair 1, 1 sits at indexes 0 and 1, labelled even, odd. The 2 at index 2 is labelled no twin. After the 2, every pair has moved one place right: 3 and 4, 5 and 6, 7 and 8, each labelled odd, even.

On the left, labelled "before the 2", the pair 1, 1 sits at indexes 0 and 1: even, odd. The next pair would start at index 2, but index 2 holds the 2, marked "no twin". It takes up one place on its own.

Now look to the right, labelled "after the 2". The pair 3, 3 sits at indexes 3 and 4, the pair 4, 4 at 5 and 6, and 8, 8 at 7 and 8. Each one is labelled odd, even. The 2 pushed every pair after it one place to the right.

That gives us the question to ask in the middle. Pick an even index and compare its number with the number just right of it:

  • If they are equal, a pair still starts at this even index, so the pairs have not moved yet. The single number is further right.
  • If they differ, the pairs have already moved. The single number is at this index or to its left.

In Example 1, index 4 holds 3 and index 5 holds 4. They differ, so the single number is at index 4 or before it, and indeed it is at index 2.

Solution Approach

Reading the pairs one by one shows why a smarter search is needed. After that, two things remain to settle: how to use the even-index check to cut the search down fast, and what to do when the index in the middle is odd. Example 1 then shows the whole search.

Reading the pairs one by one

Why not just compare indexes 0 and 1, then 2 and 3, and so on, until a pair does not match? It works, but it may read every number, so it takes O(n) time: twice as long for an array twice as big. Combining all the numbers with XOR, a bit operation that cancels out equal numbers, as on the Single Number page, also reads every number, and it ignores that the array is sorted.

Halving the range

How can the check save work? Keep two indexes, lo and hi, with the single number somewhere from lo to hi. At first that is the whole array. Check the index halfway between them, mid, and keep only the half the check points to:

  • If nums[mid] equals nums[mid + 1], the pair at mid is complete, and so is everything before it. The single number is after this pair, so lo becomes mid + 2.
  • Otherwise it is at mid or to its left, so hi becomes mid.

Each check throws away about half of what is left, so a million numbers take about 20 checks instead of a million. That is where O(log n) comes from. The range shrinks until lo and hi meet, and the number at that index is the answer. Binary Search Basics explains this halving from the beginning.

Checking only at even indexes

What if the middle index comes out odd? The check only makes sense at an even index, because only there should a pair start. So when mid is odd, step one place left to make it even. Stepping left never leaves the range: lo starts at 0 and only ever moves by 2, so it is always even, and an odd mid is always above it.

The search on Example 1

How does this play out on [1, 1, 2, 3, 3, 4, 4, 8, 8]? At first lo is 0 and hi is 8.

  1. mid is 4, which is even. Index 4 holds 3 and index 5 holds 4. They differ, so hi becomes 4.
  2. The range is 0 to 4, and mid is 2. Index 2 holds 2 and index 3 holds 3. They differ again, so hi becomes 2.
  3. The range is 0 to 2, and mid is 1, which is odd, so it steps left to 0. Index 0 and index 1 both hold 1: the pair is complete, so lo becomes 2.
  4. lo and hi are both 2, and index 2 holds the answer, 2.

Three checks for nine numbers, and each check read only two of them.

Java Solution

The method singleNonDuplicate works in these steps:

  1. First, set lo to 0 and hi to the last index, nums.length - 1. The single number lies somewhere from lo to hi.
  2. Start a loop that runs while lo is less than hi. Each time round, set mid to the index halfway between them, lo + (hi - lo) / 2.
  3. If mid is odd, that is mid % 2 == 1, move it one place left so the check happens where a pair should start.
  4. Compare nums[mid] with nums[mid + 1]. Equal moves lo to mid + 2, past the complete pair. Different moves hi to mid.
  5. When lo and hi meet, the loop ends: return nums[lo].

The main method runs both examples, then three edge cases: the single number at the start, at the end, and as the only number in the array.

Java
import java.util.Arrays;

public class SingleElementInSortedArray {

    public static int singleNonDuplicate(int[] nums) {
        int lo = 0;
        int hi = nums.length - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (mid % 2 == 1) {
                mid--;                    // check only where a pair should start
            }
            if (nums[mid] == nums[mid + 1]) {
                lo = mid + 2;             // pairs have not moved yet: answer is further right
            } else {
                hi = mid;                 // pairs have moved: answer is at mid or to its left
            }
        }
        return nums[lo];
    }

    public static void main(String[] args) {
        int[][] inputs = {
            {1, 1, 2, 3, 3, 4, 4, 8, 8},
            {3, 3, 7, 7, 10, 11, 11},
            {1, 2, 2},                    // single number at the start
            {1, 1, 2},                    // single number at the end
            {5},                          // the only number
        };
        for (int[] nums : inputs) {
            System.out.println(Arrays.toString(nums) + " -> " + singleNonDuplicate(nums));
        }
    }
}

Running it prints:

Output
[1, 1, 2, 3, 3, 4, 4, 8, 8] -> 2
[3, 3, 7, 7, 10, 11, 11] -> 10
[1, 2, 2] -> 1
[1, 1, 2] -> 2
[5] -> 5

Both examples give their expected answers, 2 and 10. Look at the line for [1, 2, 2]: the first check, at index 0, finds 1 and 2 different, so hi drops to 0 and the answer is 1. For [1, 1, 2] that same check finds the pair 1, 1 complete, so lo jumps to 2, the last index. For [5], lo and hi start equal, so the loop never runs and 5 comes straight back.

None of these reads past the end of the array, because mid stays smaller than hi while the loop runs, so nums[mid + 1] always exists. That depends on the line that makes mid even. Without it, the check at an odd index compares the second copy of one pair with the first copy of the next, which says nothing. Example 1 still prints 2, but Example 2 prints 7 instead of 10, and [1, 2, 2] throws ArrayIndexOutOfBoundsException.

The original implementation, SingleElementInSortedArray.java, is on GitHub.

Complexity

The cost is the number of checks, and each check halves the range of indexes still in play.

  • Time: O(log n), because every check reads two numbers and drops about half of the range from lo to hi, so n numbers need about log2 n checks.
  • Space: O(1), because the method keeps only lo, hi and mid, whatever the length of nums.