Single Element in a Sorted Array (LeetCode 540): Solution and Explanation
In a sorted array, every value appears exactly twice except one, which appears once. Find that single value in logarithmic time and constant space.
Watch it run step by step
Try your own input and write the code →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
- Set
l = 0andr = len(nums) - 1. - While
l <= r, computem = l + (r - l) // 2. - If
nums[m]differs from its left neighbor (ormis 0) and from its right neighbor (ormis the last index), returnnums[m]. - Compute
leftSize, the number of elements before the pair containingm:m - 1ifnums[m - 1] == nums[m], otherwisem. - If
leftSizeis odd, the single element is on the left, so setr = m - 1. - 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]
l= 0 andr= 8, som= 4 with value 3. Its left neighbor is also 3, so it is part of a pair starting at index 3.leftSize= 3, which is odd, so the single element must be to the left. Setr= 3.m= 1 with value 1. Its left neighbor is 1, so the pair starts at index 0 andleftSize= 0, which is even. Setl= 2.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 -11class Solution {
2 public int singleNonDuplicate(int[] nums) {
3 int l = 0, r = nums.length - 1;
4
5 while (l <= r) {
6 int m = l + (r - l) / 2;
7
8 if ((m - 1 < 0 || nums[m - 1] != nums[m]) &&
9 (m + 1 == nums.length || nums[m] != nums[m + 1])) {
10 return nums[m];
11 }
12
13 int leftSize = (m - 1 >= 0 && nums[m - 1] == nums[m]) ? m - 1 : m;
14
15 if (leftSize % 2 == 1) {
16 r = m - 1;
17 } else {
18 l = m + 1;
19 }
20 }
21 return -1;
22 }
23}1class Solution {
2public:
3 int singleNonDuplicate(vector<int>& nums) {
4 int l = 0, r = nums.size() - 1;
5
6 while (l <= r) {
7 int m = l + (r - l) / 2;
8
9 if ((m - 1 < 0 || nums[m - 1] != nums[m]) &&
10 (m + 1 == nums.size() || nums[m] != nums[m + 1])) {
11 return nums[m];
12 }
13
14 int leftSize = (m - 1 >= 0 && nums[m - 1] == nums[m]) ? m - 1 : m;
15
16 if (leftSize % 2 == 1) {
17 r = m - 1;
18 } else {
19 l = m + 1;
20 }
21 }
22 return -1;
23 }
24};Time and space complexity
O(log n)
Each iteration either returns or discards about half of the remaining range.
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
leftSizefrom the midpoint itself instead of from the start of its pair, which flips the parity and sends the search the wrong way. - Moving to
minstead of past it. Oncemis known to be part of a pair, usem - 1orm + 1as the new bound so the loop always shrinks. - Comparing with
nums[m - 1]whenmis 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.