Single Element in a Sorted Array - Problem

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.

Return the single element that appears only once.

Constraints: Your solution must run in O(log n) time and O(1) space.

Input & Output

Example 1 — Single Element in Middle
$ Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
💡 Note: All elements appear twice except 2 which appears once. Element 2 is at index 2.
Example 2 — Single Element at Start
$ Input: nums = [3,3,7,7,10,11,11]
Output: 10
💡 Note: All elements appear twice except 10. Element 10 is at index 4.
Example 3 — Minimum Case
$ Input: nums = [1]
Output: 1
💡 Note: Only one element in array, so it must be the single element.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 105
  • Array is sorted in ascending order
  • Every element appears exactly twice except one

Visualization

Tap to expand
Single Element in a Sorted Array INPUT Sorted Array (pairs except one) 1 1 2 3 3 4 4 8 8 Indices: 0 1 2 3 4 5 6 7 8 nums = [1,1,2,3,3,4,4,8,8] Length: 9 (odd) All pairs except one single Required: O(log n) time Required: O(1) space Use Binary Search! ALGORITHM STEPS 1 Binary Search Setup lo=0, hi=8 (even indices) 2 Find Mid (even index) mid = 4, nums[4] = 3 3 Check Pair Pattern nums[4]=3, nums[5]=4 Not equal: search left 4 Narrow Search hi=4, mid=2, check nums[2] nums[2]=2, nums[3]=3 Key Observation: Before single: pairs at even,odd After single: pairs at odd,even If nums[mid] != nums[mid+1] Single is at mid or before FINAL RESULT Binary Search Iterations: Iter 1: lo=0, hi=8, mid=4 nums[4]=3 != nums[5]=4 --> hi=4 Iter 2: lo=0, hi=4, mid=2 nums[2]=2 != nums[3]=3 --> hi=2 Iter 3: lo=0, hi=2, mid=0 nums[0]=1 == nums[1]=1 --> lo=2 Single Element: 2 lo == hi == 2 nums[2] = 2 (OK) Only 3 iterations needed! Key Insight: In a sorted array with pairs, before the single element, pairs start at even indices (0,1), (2,3), etc. After the single element, pairs start at odd indices. Binary search on even indices: if nums[mid] == nums[mid+1], the single is to the right; otherwise, it's at mid or to the left. This achieves O(log n) time, O(1) space. TutorialsPoint - Single Element in a Sorted Array | Optimal Binary Search Solution
Asked in
Facebook 25 Google 18 Amazon 15 Microsoft 12
182.0K Views
Medium Frequency
~15 min Avg. Time
3.4K 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