LeetCode #540 Medium

Single Element in a Sorted Array

Every element in a sorted array appears exactly twice, except one element that appears once. Find it in O(log n) time and O(1) space.

binary searcharraybit trick
Open on LeetCode ↗
02

Intuition

💡

Before the single element, pairs start at even indexes (0-1, 2-3, …). After it, that alignment breaks. Binary search for the first place the pairing is broken — that's where the loner hides.

03

Approach

1

The O(n) scan misses the point

XOR-ing everything, or scanning in steps of two, finds the answer — but the problem demands O(log n), which is a loud hint that the sorted structure carries information. What changes at the single element? The pair alignment.

2

Pair parity is the search signal

Left of the single element, every pair occupies indexes (even, even+1). At an even mid, if nums[mid] == nums[mid+1] the pairing is still intact — the loner must be right of the pair, so lo = mid + 2. If it differs, the break has already happened — the loner is at mid or left, so hi = mid. Force mid even first (mid -= 1 when odd) so the test is always well-formed.

3

Converge to the break point

The invariant 'loner is inside [lo, hi]' holds every round and the range halves each time, so when lo == hi it points exactly at the single element. No verification pass needed — return nums[lo].

04

Solution & live demo

python
1class Solution:
2 def singleNonDuplicate(self, nums):
3 lo, hi = 0, len(nums) - 1
4 while lo < hi:
5 mid = (lo + hi) // 2
6 if mid % 2 == 1:
7 mid -= 1
8 if nums[mid] == nums[mid + 1]:
9 lo = mid + 2
10 else:
11 hi = mid
12 return nums[lo]
05

Edge cases

Single element is first

The very first pair test fails (nums[0] != nums[1]), so hi collapses to 0 immediately.

Single element is last

Every pair test passes; lo marches in steps of 2 to the final index.

Array of length 1

Loop never runs (lo == hi already) — return the only element.

06

Complexity

Time
O(log n)
Space
O(1)
The range halves every iteration; only two indexes are ever compared.