Algo-Sim › Binary Search
Single Element in a Sorted Array
Medium · Binary Search · step through it in Java, Python and C++ on your own input
Every value appears twice except one. Pairs start at even indices before it and odd ones after it, so compare nums[mid] with nums[mid ^ 1].
Problem
The sorted array nums contains every value exactly twice, except for one value that appears once. Return that value in O(log n) time and O(1) extra space.
Constraints
- 1 ≤ nums.length ≤ 10⁵ (odd)
- 0 ≤ nums[i] ≤ 10⁵
- nums is sorted; exactly one value appears once
Edge cases to test
- One element
- The single value is first
- The single value is last
Follow-up questions
- What if the array is not sorted?
- XOR every value: pairs cancel and the single one remains (LC 136), O(n) time, O(1) space.
- Why does
mid ^ 1work? - It is mid’s partner index (even ↔ odd). Before the single value pairs start at even indices, after it at odd ones, so a matching partner says the single is to the right.
Solution
Java
public int singleNonDuplicate(int[] nums) {
int lo = 0, hi = nums.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == nums[mid ^ 1]) lo = mid + 1;
else hi = mid;
}
return nums[lo];
}Python
def single_non_duplicate(nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] == nums[mid ^ 1]: lo = mid + 1
else: hi = mid
return nums[lo]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int singleNonDuplicate(vector<int> &nums) {
int lo = 0, hi = nums.size() - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == nums[mid ^ 1]) lo = mid + 1;
else hi = mid;
}
return nums[lo];
}
};
More Binary Search problems
- Binary Search (Easy)
- Search Insert Position (Easy)
- Sqrt(x) (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Koko Eating Bananas (Medium)
- Kth Smallest Element in a Sorted Matrix (Medium)
- Allocate Minimum Pages (Hard)
- Median of Two Sorted Arrays (Hard)
- Time Based Key-Value Store (Medium)