Single Element in a Sorted Array - Problem
You're given a sorted array with a unique twist - every element appears exactly twice, except for one lonely element that appears only once. Your mission? Find that single element!
Here's the catch: your solution must be lightning fast with O(log n) time complexity and use only O(1) extra space. This means you can't simply iterate through the entire array - you need to be clever!
Example: In [1,1,2,3,3,4,4,8,8], the element 2 appears only once while all others appear twice.
Think about how the sorted property combined with the pairing pattern can help you eliminate half the search space at each step!
Input & Output
example_1.py โ Python
$
Input:
[1,1,2,3,3,4,4,8,8]
โบ
Output:
2
๐ก Note:
The element 2 appears only once while all other elements (1,3,4,8) appear exactly twice
example_2.py โ Python
$
Input:
[3,3,7,7,10,11,11]
โบ
Output:
10
๐ก Note:
Elements 3,7,11 appear twice each, but 10 appears only once
example_3.py โ Python
$
Input:
[1]
โบ
Output:
1
๐ก Note:
Edge case: array with single element - that element appears only once
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 106
- nums.length is always odd
- Array is sorted in non-decreasing order
- Every element appears exactly twice except one element which appears once
Visualization
Tap to expand
Understanding the Visualization
1
Normal Pattern
In arrays with only pairs, elements at even indices (0,2,4...) match their next neighbor
2
Disruption Point
The single element breaks this pattern - pairs after it shift to odd indices
3
Binary Decision
Check if mid (even) equals mid+1 to determine which side has the disruption
Key Takeaway
๐ฏ Key Insight: The single element acts like a shift point - pairs before it align with even indices, pairs after it align with odd indices. Binary search leverages this pattern to achieve O(log n) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code