540. Single Element in a Sorted Array
At a Glance
- Topic: binary-search
- Pattern: Binary Search (Pair invariant)
- Difficulty: Medium
- Companies: Google, Amazon, Meta, Apple, Adobe
- Frequency: Medium
- LeetCode: 540
Problem (one-liner)
Even-length sorted array where every value appears exactly twice except one value once; return that single element in O(log n) time and O(1) space.
Recognition Cues
- Pairs in sorted order then one singleton
- “Logarithmic time” on array with pair structure
- After discarding half, remaining side still has even pair structure until singleton isolated
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force —
O(n)— XOR all values (works but ignores “sorted” hint) or scan pairs. - Better —
O(n)— walk pairs by twos. - Optimal —
O(log n)time /O(1)space — alignmidto even index and compare with neighbor to see which side keeps odd pattern.
Optimal Solution
Go
func singleNonDuplicate(nums []int) int {
left, right := 0, len(nums)-1
for left < right {
mid := left + (right-left)/2
if mid%2 == 1 {
mid--
}
if nums[mid] != nums[mid+1] {
right = mid
} else {
left = mid + 2
}
}
return nums[left]
}JavaScript
function singleNonDuplicate(nums) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
let mid = left + Math.floor((right - left) / 2);
if (mid % 2 === 1) {
mid--;
}
if (nums[mid] !== nums[mid + 1]) {
right = mid;
} else {
left = mid + 2;
}
}
return nums[left];
}Walkthrough
nums = [1,1,2,3,3,4,4,8,8]
| step | left | right | even mid | pair at mid? | move |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 3==3 | left = 6 |
| 2 | 6 | 8 | 6 | 4!=8 | right = 6 |
Answer nums[6] = 4. Invariant: singleton always in current window; pair alignment tells which side is “clean”.
Edge Cases
- Singleton at start or end.
- Size 1 array.
- All pairs except first element (duplicated second position).
Pitfalls
- Forgetting to snap
midto even index before reading the pair. - Off-by-two when moving
leftafter a full match.
Similar Problems
- 704. Binary Search — same interval halving structure.
- 136. Single Number — XOR linear alternative exploiting pairwise cancellation.
- 153. Find Minimum in Rotated Sorted Array — binary search guided by structural asymmetry.
Variants
- Two single elements — problem changes; need different strategy.
- Unsorted — fall back to XOR or hash counts.
Mind-Map Tags
#binary-search #pairs #even-index-invariant #sorted-structure
Last updated on
Spotted something unclear or wrong on this page?