You are given a sorted array nums. Every value in it appears exactly twice, side by side, except for one value that appears only once.
Return that lone value. Your solution should take O(log n) time and O(1) extra space.
Example 1
Input: nums = [3, 3, 5, 5, 6, 6, 8, 10, 10, 11, 11] Output: 8 Why: 8 has no twin
2 more examples and the constraints
Example 2
Input: nums = [4, 7, 7] Output: 4 Why: the lone value can be the first one
Example 3
Input: nums = [2] Output: 2 Why: a single number is alone by definition
Constraints
- 1 ≤ length of nums ≤ 100,000
- 0 ≤ each nums[i] ≤ 100,000
- nums is sorted in non-decreasing order
- Exactly one value appears once; every other value appears twice
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check pairs in orderO(n)
- Binary search on pairsO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Reads for 100,000 numbers | Verdict |
|---|---|---|---|
| Check pairs in order | O(n) | Correct; misses O(log n) | |
| Binary search on pairs | O(log n) | Best; about 17 checks |
n = length of nums.
Edge cases to test
- Only one number. [2]: lo and hi start equal, so the loop never runs and nums[0] is returned.
- Single value first. [4, 7, 7]: the first pair check already fails, and hi shrinks to 0.
- Single value last. [1, 1, 2, 2, 9]: every check passes and lo walks up to the last index.
- Zero as the answer. [0, 5, 5] returns 0; do not treat 0 as "not found".
Common mistakes
- Comparing nums[mid] with nums[mid + 1] at an odd mid, where a match means the opposite of what it means at an even mid.
- Setting hi = mid − 1 when the pair is broken, which can skip the single value sitting at mid.
- Using XOR or a linear scan and calling it done, when the question asks for O(log n).
How to talk through it
- 1Clarify. Are twins always next to each other? Is there always exactly one single value? Can the array have one element?
- 2Give the linear scan. Check pairs two at a time, or XOR everything. Both are O(n); the problem wants O(log n).
- 3Find the flip. Before the single value pairs start on even indices, after it on odd ones. That is a property binary search can use.
- 4Code the search. Snap mid to even, compare with mid + 1, then lo = mid + 2 or hi = mid.
- 5Test out loud. Run [2], [4, 7, 7] and [1, 1, 2, 2, 9] so the first, middle and last positions are all covered.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?