Single Element in a Sorted Array
Master this topic with zero to advance depth.
Single Element in a Sorted Array
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. Your solution must run in time and space.
Examples
Level I: XOR Manipulation
Intuition
XORing a number with itself results in 0. XORing 0 with any number results in that number. If we XOR all elements, the pairs will cancel out, leaving the single element.
Detailed Dry Run
nums = [1,1,2] 1 ^ 1 ^ 2 = 0 ^ 2 = 2. Result: 2.
Level II: Linear Scan (Pairs)
Intuition
Since the array is sorted, we can check elements in pairs. If nums[i] is not equal to nums[i+1], then nums[i] is the single element.
Detailed Dry Run
nums = [1,1,2,3,3]
- i=0: nums[0]==nums[1] (1==1). Continue.
- i=2: nums[2]!=nums[3] (2!=3). Return nums[2]=2.
Level III: Optimal (Binary Search on Even Indices)
Intuition
In a paired array, pairs start at even indices: (0,1), (2,3), etc. Before the single element, nums[even] == nums[even+1]. After the single element, this pattern breaks. We search for the first index where nums[even] != nums[even+1].
Detailed Dry Run
| Step | L | R | Mid | Mid_Even | nums[M_E] == nums[M_E+1] | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 4 | 3 == 4 (No) | R = 4 |
| 2 | 0 | 4 | 2 | 2 | 2 == 3 (No) | R = 2 |
| Exit | 2 | 2 | - | - | - | Return nums[2] = 2 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.