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
Index Parity Pattern AnalysisArray: [1, 1, 2, 3, 3, 4, 4, 8, 8]101122333445468788Pattern Analysis:Before single element:Pairs at EVEN indices (0,2,4...)After single element:Pairs at ODD indices (1,3,5...)Binary Search Steps:Step 1: mid=4nums[4]=3nums[5]=43โ‰ 4 โ†’ Go LEFTStep 2: mid=2nums[2]=2nums[3]=32โ‰ 3 โ†’ Found!๐ŸŽฏ Key Insight:Single element disrupts the even-index pairing pattern!
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 25
42.3K Views
Medium-High Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen