Single Element in a Sorted Array
You are given a sorted array of integers in which every element appears exactly twice except for one element that appears exactly once. Return that single element. Your solution must run in O(log n) time and O(1) space.
Open official problem prompt ↗Locate the one unpaired value in a sorted array without scanning every element.
Imagine dancers lined up in couples. Up to some point every couple stands shoulder to shoulder; the moment one person is missing a partner, everyone after shifts by one spot. You binary-search for exactly where the neat pairing first fails.
- Input
- nums = [1,1,2,3,3,4,4,8,8]
- Output
- 2
- Why
- Every value forms a pair except 2, which appears only once.
1 <= nums.length <= 10^50 <= nums[i] <= 10^5nums is sorted in non-decreasing orderExactly one element appears once; all others appear exactly twice