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
Example 1
Output: 2
Example 2
Output: 10
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.
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
Halving the range
How can the check save work? Keep two indexes, lohilohimid
- If
equalsnums[mid] , the pair atnums[mid + 1] is complete, and so is everything before it. The single number is after this pair, somid becomeslo .mid + 2 - Otherwise it is at
or to its left, somid becomeshi .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 lohi
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 midlomid
The search on Example 1
How does this play out on [1, 1, 2, 3, 3, 4, 4, 8, 8]lohi
is 4, which is even. Index 4 holds 3 and index 5 holds 4. They differ, somid becomes 4.hi- The range is 0 to 4, and
is 2. Index 2 holds 2 and index 3 holds 3. They differ again, somid becomes 2.hi - The range is 0 to 2, and
is 1, which is odd, so it steps left to 0. Index 0 and index 1 both hold 1: the pair is complete, somid becomes 2.lo andlo are both 2, and index 2 holds the answer, 2.hi
Three checks for nine numbers, and each check read only two of them.
Java Solution
The method singleNonDuplicate
- First, set
to 0 andlo to the last index,hi . The single number lies somewhere fromnums.length - 1 tolo .hi - Start a loop that runs while
is less thanlo . Each time round, sethi to the index halfway between them,mid .lo + (hi - lo) / 2 - If
is odd, that ismid , move it one place left so the check happens where a pair should start.mid % 2 == 1 - Compare
withnums[mid] . Equal movesnums[mid + 1] tolo , past the complete pair. Different movesmid + 2 tohi .mid - When
andlo meet, the loop ends: returnhi .nums[lo]
The main
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:
[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]hi[1, 1, 2]lo[5]lohi
None of these reads past the end of the array, because midhinums[mid + 1]mid[1, 2, 2]ArrayIndexOutOfBoundsException
The original implementation,
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
tolo , so n numbers need about log2 n checks.hi - Space: O(1), because the method keeps only
,lo andhi , whatever the length ofmid .nums