LeetCode #540 Medium

Single Element in a Sorted Array

Single Element in a Sorted Array is LeetCode 540 (Medium). The array is sorted, every value appears exactly twice except one value that appears once. Return that value.

  • The solution must run in O(log n) time and O(1) extra space.

That rules out XOR-ing everything or scanning pairs, which both read all n elements.

Constraints
  • 1 <= nums.length <= 10⁵
  • 0 <= nums[i] <= 10⁵
binary searcharraybit trick
Open on LeetCode ↗
02

Intuition

Look at the array as pairs starting at even indices: (0,1), (2,3), (4,5) and so on.

  • Before the single element, every pair is intact: nums[2k] == nums[2k+1].
  • From the single element on, everything has shifted by one, so nums[2k] no longer equals nums[2k+1].

So the question "is the pair at this even index intact?" is yes up to some point and no after it. That turns the problem into a binary search for the first broken pair, and the single element is the first element of that pair.

How to spot this pattern

No target value to compare against, but a yes/no question that is true on one side of the answer and false on the other. That shape means binary search on the condition, even though nothing here is a target.

03

Approach

Try it first

Before reading on, write [1,1,2,3,3,4,4] with indices and circle each pair that starts at an even index. Which pairs are intact, and where does the first broken one start?

1

Search the whole array

Set lo = 0 and hi = n - 1. The single element is always inside [lo, hi], and the loop runs while lo < hi, so it stops when one index is left.

2

Move mid to an even index

Compute mid and, if it is odd, subtract 1. Pairs only start at even indices before the single element, so testing from an even index is what makes "intact or broken" meaningful.

3

Intact pair: go right past it

If nums[mid] == nums[mid + 1], everything up to mid + 1 is still correctly paired, so the single element is to the right. Set lo = mid + 2; both elements of the pair are excluded.

4

Broken pair: keep mid

Otherwise the shift has already happened at or before mid, so set hi = mid. mid itself may be the single element, so it must stay in the range.

5

Return the last index left

When lo == hi, that index holds the single element. mid + 1 is always valid inside the loop: mid is even and below hi, and hi is always even too, so mid + 1 <= hi.

04

Code in Python, C++ and Java

▶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]
10lo1122333445468788hisearch indices 0 to 8
lo0
hi8
Every value appears twice except one. Pairs are checked only where they should start, at even indices: before the single element they are intact, and from it onward they are broken.
10lo11223334mid45468788himiddle of 0 to 8 is index 4
lo0
hi8
mid4
Look at the middle of the range, so that either half can be thrown away after one comparison.
broken10lo11223334himid454687883 and 4 differ → answer is at or before index 4
pair3, 4broken
hi4
The pair at index 4 is broken, so the shift has already happened: the single element is at index 4 or earlier. Index 4 itself may be the answer, so hi stops there instead of going past it.
broken10lo1122mid3334hi45468788middle of 0 to 4 is index 2
lo0
hi4
mid2
Look at the middle of the range, so that either half can be thrown away after one comparison.
brokenbroken10lo1122himid3334454687882 and 3 differ → answer is at or before index 2
pair2, 3broken
hi2
The pair at index 2 is broken, so the shift has already happened: the single element is at index 2 or earlier. Index 2 itself may be the answer, so hi stops there instead of going past it.
brokenbroken10lo11mid22hi333445468788middle of 0 to 2 is index 1
lo0
hi2
mid1
Look at the middle of the range, so that either half can be thrown away after one comparison.
brokenbroken10lomid1122hi333445468788index 1 is odd → use 0, where a pair starts
mid0was 1
An odd index is the second half of a pair, so comparing it with the next element would mix two pairs. Stepping back one puts mid at the start of a pair.
pairbrokenbroken10mid1122lo hi3334454687881 and 1 match → answer is after index 1
pair1, 1intact
lo2
The pair at index 0 is intact, so nothing has shifted yet: every element up to index 1 is correctly paired. The single element is further right, so lo jumps past both elements of the pair.
pairbrokenbroken101122lo hi333445468788one index left → answer 2
lo = hi2
result2
lo and hi meet at index 2. It is the only place the single element can be, so the answer is 2. Only 3 pairs were compared out of 9 elements.
05

Common pitfalls

Comparing from an odd mid

✗ Wrong
mid = (lo + hi) // 2
if nums[mid] == nums[mid + 1]:
    lo = mid + 2
✓ Right
mid = (lo + hi) // 2
if mid % 2 == 1:
    mid -= 1
if nums[mid] == nums[mid + 1]:
    lo = mid + 2

An odd index is the second half of a pair, so nums[mid] and nums[mid + 1] come from two different pairs and their equality means nothing. On [1,2,2], mid = 1 sees 2 == 2, jumps to lo = 3, and reads past the end of the array.

Looping while lo <= hi

✗ Wrong
while lo <= hi:
✓ Right
while lo < hi:

With <= the loop runs once more when one index is left. On [1,1,2], lo and hi both reach 2, mid is 2, and nums[mid + 1] is index 3, outside the array.

06

Edge cases

Only one element, [7]

lo == hi from the start, so the loop never runs and nums[0] is returned.

The single element is last, [1,1,2,2,3]

Every tested pair is intact, so lo keeps moving right until it reaches index 4. The loop ends there and returns 3.

07

Complexity

Time
O(log n)
Space
O(1)
Each step at least halves the range [lo, hi], and only two indices and one comparison are used per step.
08

Single Element in a Sorted Array FAQ

Why is the single element always at an even index?

Everything before it is made of complete pairs, so the number of elements before it is even. Its index equals that count, so it is even. The same count argument shows n is odd, so hi = n - 1 starts even.

What is the mid ^ 1 trick?

mid ^ 1 flips the lowest bit, giving mid + 1 for even mid and mid - 1 for odd mid: the index of its partner in a healthy pair. Testing nums[mid] == nums[mid ^ 1] replaces the even-adjust step; on a match set lo = mid + 1, otherwise hi = mid.

Would XOR of all elements work?

It gives the right value, because each pair cancels to 0, and it does not even need the array to be sorted. But it reads every element, so it is O(n) and does not meet the O(log n) requirement.