Single Element in a Sorted Array (LeetCode 540): Solution and Explanation

Medium
Array
Binary Search

In a sorted array, every value appears exactly twice except one, which appears once. Find that single value in logarithmic time and constant space.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

There are two easy linear answers. You can XOR every element together, since paired values cancel out and only the single one remains, or you can walk the array two at a time and stop where a pair does not match. Both are O(n). The requirement of O(log n) means you need to use the sorted order, which neither of those does.

Look at what the single element does to the layout of the pairs. Before it, every pair starts at an even index: positions 0 and 1, 2 and 3, and so on. After it, everything is shifted by one, so pairs start at odd indices. The single element sits exactly at the point where this pattern breaks, and that breaking point is what binary search can find.

The reference code expresses the same idea by counting. At a midpoint m, first check whether nums[m] differs from both neighbors; if so, it is the answer. Otherwise m belongs to a pair. Count the elements strictly to the left of that pair: if the pair is m - 1 and m, that count is m - 1, and if the pair is m and m + 1, it is m. If the count is odd, the left side cannot be made entirely of pairs, so the single element is on the left. If the count is even, the left side is all pairs and the single element lies to the right.

Each step throws away the half that is fully paired, so the search finishes in logarithmic time.

Approach: Binary search on pair parity

  1. Set l = 0 and r = len(nums) - 1.
  2. While l <= r, compute m = l + (r - l) // 2.
  3. If nums[m] differs from its left neighbor (or m is 0) and from its right neighbor (or m is the last index), return nums[m].
  4. Compute leftSize, the number of elements before the pair containing m: m - 1 if nums[m - 1] == nums[m], otherwise m.
  5. If leftSize is odd, the single element is on the left, so set r = m - 1.
  6. If it is even, the left part is all pairs, so set l = m + 1.

Step-by-step example

nums = [1,1,2,3,3,4,4,8,8]
  1. l = 0 and r = 8, so m = 4 with value 3. Its left neighbor is also 3, so it is part of a pair starting at index 3.
  2. leftSize = 3, which is odd, so the single element must be to the left. Set r = 3.
  3. m = 1 with value 1. Its left neighbor is 1, so the pair starts at index 0 and leftSize = 0, which is even. Set l = 2.
  4. m = 2 with value 2. Its neighbors are 1 and 3, both different, so the function returns 2.

Code: Python, Java, C++

1class Solution:
2    def singleNonDuplicate(self, nums: List[int]) -> int:
3        l, r = 0, len(nums) - 1
4        
5        while l <= r:
6            m = l + ((r - l) // 2)
7            
8            if ((m - 1 < 0 or nums[m - 1] != nums[m]) and 
9                (m + 1 == len(nums) or nums[m] != nums[m + 1])):
10                return nums[m]
11                
12            leftSize = m - 1 if nums[m - 1] == nums[m] else m
13            
14            if leftSize % 2:
15                r = m - 1
16            else:
17                l = m + 1
18        return -1

Time and space complexity

Time

O(log n)

Each iteration either returns or discards about half of the remaining range.

Space

O(1)

Only a few index variables are used.

Other approaches

XOR of all elements (time O(n), space O(1))

XOR every value together. Each pair cancels to zero, leaving the single value. It is elegant and works even on unsorted input, but it is linear and ignores the sorted order.

Binary search on even indices (time O(log n), space O(1))

Keep m even by decrementing it when it is odd, then compare nums[m] with nums[m + 1]. If they match, the single element is to the right (l = m + 2), otherwise it is at or before m (r = m). It needs fewer boundary checks.

Common mistakes

  • Counting leftSize from the midpoint itself instead of from the start of its pair, which flips the parity and sends the search the wrong way.
  • Moving to m instead of past it. Once m is known to be part of a pair, use m - 1 or m + 1 as the new bound so the loop always shrinks.
  • Comparing with nums[m - 1] when m is 0 in Java or C++, which reads out of bounds. Python silently reads the last element, which only works because the array's first and last values cannot be equal.
  • Returning the index instead of the value. The problem asks for the single element itself.

Frequently asked questions

Why does pair parity tell us which side to search?

Before the single element, pairs start at even indices, so the number of elements before any pair is even. After it, pairs are shifted by one and that count becomes odd. Checking the parity at the midpoint shows which side the shift happened on.

Can you use XOR for Single Element in a Sorted Array?

Yes, XOR of all elements returns the single value, but it takes O(n) time. The problem asks for O(log n), which requires binary search over the sorted order.

What is the time complexity?

The binary search solution runs in O(log n) time and O(1) space.

Does the array length tell you anything?

The length is always odd, since there are pairs plus one single value. That is why the single element must be on the side whose element count is odd.