Single Element in a Sorted Array, solved with binary search
To find the single element in a sorted array where every other value appears exactly twice, binary search on even indexes: if the value at an even index equals its right neighbor, the lone value lies further right; otherwise it is at that index or to its left. That runs in O(log n) time and O(1) extra space.
By Evin JohnPublished 8 min read
What the problem asks
You get a list of integers in non-decreasing order. Every value in it shows up exactly two times, side by side, except one value that shows up once. Return the value that has no partner. The catch that makes this an interview question is the time limit: the interviewer wants better than reading the whole list, which means logarithmic time.
| Sorted list | Lone value | Note |
|---|---|---|
| [3, 3, 5, 8, 8] | 5 | The odd one out sits in the middle |
| [1, 4, 4, 6, 6] | 1 | It can be the very first entry |
| [2, 2, 7, 7, 9] | 9 | It can be the very last entry |
| [10] | 10 | A list of one element is valid input |
| [-6, -6, -2, 0, 0] | -2 | Negative values change nothing |
Notice that the length is always odd: some number of pairs plus one. That fact is what makes the index trick below work, so it is worth saying out loud when you restate the problem. Good clarifying questions: is the list guaranteed non-empty, and is it guaranteed that exactly one value is unpaired? If the guarantee can be broken, ask what to return.
Two slow but correct answers
The first idea most people have is to walk the list two steps at a time. Compare position 0 with position 1, then 2 with 3, and so on. The first time a pair disagrees, the left member of that pair is the answer. If every pair matches, the answer is the last element. This is O(n) time and O(1) space, and it already uses the pairing structure.
def lone_value_scan(nums):
for i in range(0, len(nums) - 1, 2):
if nums[i] != nums[i + 1]:
return nums[i]
return nums[-1]The second classic is XOR. A value XORed with itself is zero, and XOR is order-independent, so folding XOR across the whole list cancels every pair and leaves the lone value. It is a neat trick and it does not even need the list to be sorted. That is exactly its weakness here: it ignores the one property the problem handed you, so it cannot beat linear time.
def lone_value_xor(nums):
acc = 0
for x in nums:
acc ^= x
return accThe observation that unlocks binary search
Write the indexes under the values in [3, 3, 5, 8, 8]. The pair of 3s sits at indexes 0 and 1, so it starts on an even index. The lone 5 is at index 2. The pair of 8s sits at 3 and 4, so it starts on an odd index. The single element shifts every later pair by one position.
So for any even index i: if nums[i] equals nums[i + 1], the pairs up to i are still aligned, and the lone value must be to the right of i + 1. If they differ, the alignment has already broken, so the lone value is at i or somewhere to its left. That is a yes-or-no test that splits the search space, which is all binary search needs.
- Set the windowLet
leftbe 0 andrightbe the last index. The answer is always inside [left, right]. - Pick an even midpointCompute the middle index. If it is odd, step back by one so it points at the first slot of a would-be pair.
- Test the pairIf
nums[mid] == nums[mid + 1], the left part is cleanly paired: movelefttomid + 2. Otherwise setrighttomid. - Stop when the window closesWhen
left == right, that index holds the lone value.
Why is mid + 1 always a valid index? Because left and right both stay even, and while left < right the even midpoint is at most right - 2. The list never gets read past its end.
Python and JavaScript solutions
def lone_value(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if mid % 2 == 1:
mid -= 1
if nums[mid] == nums[mid + 1]:
left = mid + 2
else:
right = mid
return nums[left]function loneValue(nums) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
let mid = (left + right) >> 1;
if (mid % 2 === 1) mid--;
if (nums[mid] === nums[mid + 1]) {
left = mid + 2;
} else {
right = mid;
}
}
return nums[left];
}A popular variant skips the even snap and compares nums[mid] with nums[mid ^ 1]. For an even mid, mid ^ 1 is the next index; for an odd mid, it is the previous one. In both cases it is the slot that would be mid's partner if no lone value came before it. Then you move left = mid + 1 on a match and right = mid otherwise. It is shorter, but if you use it, be ready to explain the XOR on the index, because interviewers often ask.
Tracing one input
Take [1, 1, 2, 2, 4, 6, 6]. The window starts as indexes 0 to 6. The midpoint is 3, which is odd, so it snaps to 2. nums[2] is 2 and nums[3] is 2, a match, so left becomes 4. Now the window is 4 to 6, the midpoint is 5, which snaps to 4. nums[4] is 4 and nums[5] is 6, no match, so right becomes 4. The window has closed on index 4, and the answer is 4.
Cost of each approach
| Method | Time | Memory | Uses sortedness? |
|---|---|---|---|
| Count with a dictionary | O(n) | O(n) | No |
| XOR of all values | O(n) | O(1) | No |
| Step through pairs | O(n) | O(1) | Partly |
| Binary search on even indexes | O(log n) | O(1) | Yes, fully |
Edge cases worth testing
- A one-element list. The loop never runs and the function returns
nums[0]. - The lone value at index 0, as in [1, 4, 4, 6, 6]. The first comparison fails and
rightwalks down to 0. - The lone value at the last index. Every comparison matches and
leftclimbs to the end. - Long runs of pairs with large gaps between values, such as [-1000, -1000, 5, 999, 999]. Only equality matters, so spacing is irrelevant.
- Very large lists in a language with fixed-width integers.
(left + right) / 2can overflow there;left + (right - left) / 2cannot. In Python and in JavaScript at these sizes it is not an issue.
Where candidates slip
- Comparing with the wrong neighbor. Checking
nums[mid - 1]at an even mid tells you nothing useful about alignment. The partner of an even index is the next slot. - Moving `left` to `mid + 1` instead of `mid + 2` in the even-snap version. That puts
lefton an odd index and the parity logic falls apart. - Setting `right = mid - 1` on a mismatch. The lone value can be at mid itself, so mid has to stay in the window.
- Presenting XOR as the final answer. It is a good opening line, but it is linear, and the sorted input is a strong hint that the interviewer wants a logarithmic search.
- Not handling the length-one case in languages where reading
nums[mid + 1]past the end throws or returns garbage.
Saying it out loud
Fictional example
- Candidate
- XOR over everything would cancel the pairs, but that is linear and does not use the sorting. Let me look at the indexes instead.
- Candidate
- Before the lone value, every pair begins at an even index. After it, every pair begins at an odd one. So at an even midpoint, if the next value matches, the left side is clean and I go right past the pair. If it does not match, the answer is here or to the left.
- Candidate
- Each step halves the window, so it is logarithmic time and constant space. A one-element list just returns its only value.
More binary search problems in this batch
This page is part of a set on searching by a yes-or-no test. Search in Rotated Sorted Array II also decides which half to keep by comparing a few positions, while Minimize Max Distance to Gas Station moves the search from indexes to a range of real numbers. For Magnetic Force Between Two Balls, the test becomes a greedy feasibility check. For broader preparation, see the algorithm interview questions guide.
Practicing with Natively
When you rehearse a problem like this, Natively can read a screenshot of the statement and suggest an approach, which is a handy second opinion after you have written your own version. It can also transcribe a mock round on your computer, so you can check later whether you explained the parity argument clearly or skipped it. More on that in the AI interview assistant overview.
Questions people ask
How do you find the single element in a sorted array in O(log n)?
Binary search on even indexes. If the value at an even index matches the next one, every pair to the left is aligned, so search the right half; otherwise the lone value is at that index or to its left.
Why does the XOR solution not count as optimal here?
XOR cancels every pair and leaves the lone value, but it reads every element, so it is O(n). It ignores the sorted order, which is what allows a logarithmic search.
Why must the midpoint be even?
Before the lone value, pairs start at even indexes. Snapping mid to an even index means nums[mid] and nums[mid + 1] would be a pair if nothing unusual came earlier, so a mismatch proves the break is at or before mid.
What edge cases should I test?
A list of one element, the lone value at the first index, the lone value at the last index, and negative numbers. All four should return without reading past the end of the list.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
