Unpaired Value in a Sorted Array
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement find_single_element(nums: List[int]) -> int. You receive a nondecreasing integer list nums in which every value occurs twice, with the exception of a single value that occurs once. Identify and return that lone unpaired integer.
Your algorithm must run in O(log n) time and allocate only O(1) auxiliary memory.
Examples
Example 1
- Input:
nums = [4, 4, 6, 9, 9, 14, 14] - Output:
6 - Explanation:
4,9, and14each appear as adjacent pairs, whereas6sits alone at index2.
Example 2
- Input:
nums = [0, 0, 5, 5, 8, 8, 13, 21, 21] - Output:
13 - Explanation: The pairs
(0, 0),(5, 5), and(8, 8)fill indices0..5before13appears once at index6, followed by(21, 21).
Constraints
1 <= len(nums) <= 10^5(len(nums)is guaranteed to be odd)0 <= nums[i] <= 10^5numsis sorted in nondecreasing order, with exactly one element occurring once and all other elements occurring twice.- Time complexity must be
O(log n)and extra space complexity must beO(1).
Step-by-step walkthrough
Restate the problem and why O(n) is too slow
We receive a nondecreasing integer list
numsin which every value appears twice, except for one value that appears once. Becausenumsis sorted, matching duplicates always sit next to each other, andlen(nums)is always odd (2k + 1).Without a runtime cap, we could walk
numsin steps of2and return the first value that differs from its right neighbor:def find_single_linear(nums: list[int]) -> int: for i in range(0, len(nums) - 1, 2): if nums[i] != nums[i + 1]: return nums[i] return nums[-1]That scan works, and folding every element with bitwise XOR (
a ^ a == 0) works too. However, when the unpaired number sits near the back, scanning inspects nearly allnentries inO(n)time. To meet theO(log n)time andO(1)auxiliary space bounds, we need anO(1)probe near the midpoint that reveals which half holds the unpaired number so we can discard the other half immediately.Key observation: the unpaired element shifts every later pair
Track the index parity (even vs. odd) where each pair begins. To the left of the lone number, every pair occupies two slots, starting cleanly at an even index (
0, 2, 4, ...) and ending at an odd index (1, 3, 5, ...).The lone number occupies just one slot, pushing every pair after it one position to the right so that all subsequent pairs begin at odd indices and end at even indices! Inspect Example 1 (
[4, 4, 6, 9, 9, 14, 14]):index: 0 1 2 3 4 5 6 parity: E O E O E O E value: [ 4, 4, 6, 9, 9, 14, 14 ] grouping: +---+ ^ +---+ +----+ (even, solo (odd, (odd, odd) at E! even) even)Two properties follow directly from this layout: 1. The unpaired value always sits at an even index, because only intact pairs of length
2precede it. 2. At any even indexi: - Ifnums[i] == nums[i + 1], the(even, odd)pair starting atiis still aligned, so the unpaired value must sit strictly to the right (at indexi + 2or higher). - Ifnums[i] != nums[i + 1], pair alignment is already broken ati, so the unpaired value must sit atior to its left.Turn the even-index check into binary search
Maintain a window
nums[left..right]with a clean loop invariant (a condition true at the start of every iteration): bothleftandrightare even indices, and the unpaired value lies insidenums[left..right].Initially,
left = 0is even, andright = len(nums) - 1is also even becauselen(nums)is odd. Whileleft < right: 1. Setmid = (left + right) // 2. 2. Ifmidis odd (mid % 2 == 1), decrementmidby1to snap it to the even index right before it. Sinceleftis even andmid >= left, subtracting1from an oddmidstays>= left. 3. Why isnums[mid + 1]always in bounds? Bothmidandrightare even withmid < right, somid <= right - 2, meaningmid + 1 < right <= len(nums) - 1. 4. Comparenums[mid]withnums[mid + 1]: - Equal -> intact pair at(mid, mid + 1), so advanceleft = mid + 2(still even!). - Unequal -> alignment is already broken, so pullright = mid(still even, keepingmidbecausenums[mid]itself could be the lone number!).Once
left == right, the window holds a single index, andnums[left]is the answer.Trace both examples step by step
Trace Example 1:
nums = [4, 4, 6, 9, 9, 14, 14](left = 0,right = 6):Iter 1: left=0, right=6 -> mid=(0+6)//2 = 3 (odd -> mid -= 1 -> mid = 2) nums[2]=6, nums[3]=9 (not equal -> alignment broken at or before 2!) right = 2 Iter 2: left=0, right=2 -> mid=(0+2)//2 = 1 (odd -> mid -= 1 -> mid = 0) nums[0]=4, nums[1]=4 (equal -> intact pair before lone value!) left = 0 + 2 = 2 Stop: left == right == 2 -> return nums[2] = 6Now trace Example 2:
nums = [0, 0, 5, 5, 8, 8, 13, 21, 21](left = 0,right = 8):Iter 1: left=0, right=8 -> mid=(0+8)//2 = 4 (even) nums[4]=8, nums[5]=8 (equal -> intact pair!) left = 4 + 2 = 6 Iter 2: left=6, right=8 -> mid=(6+8)//2 = 7 (odd -> mid -= 1 -> mid = 6) nums[6]=13, nums[7]=21 (not equal -> alignment broken!) right = 6 Stop: left == right == 6 -> return nums[6] = 13Complete solution
Putting everything together gives the complete
O(log n)time,O(1)space implementation:from typing import Any, Dict, List, Optional, Set, Tuple def find_single_element(nums: List[int]) -> int: # Search window nums[left..right]; invariant: both left and right are always even indices, # and the single unique element sits at some even index inside [left, right]. left = 0 right = len(nums) - 1 # Stop when left == right: a 1-element window must hold the unique element. while left < right: mid = (left + right) // 2 # Force mid to be even so (mid, mid + 1) tests the start of a normal pair slot. # Since left is even and mid >= left, subtracting 1 from an odd mid stays >= left. if mid % 2 == 1: mid -= 1 # Because both mid and right are even with mid < right, mid + 1 < right <= len(nums) - 1, # so nums[mid + 1] is always within bounds. if nums[mid] == nums[mid + 1]: # Pair at (mid, mid + 1) is intact, so no shift has occurred yet; search after this pair. left = mid + 2 else: # Pair alignment is already broken at mid, so the unique element is at mid or to its left. right = mid return nums[left]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a long row of theater seats numbered 0, 1, 2, 3, ... filled from left to right by couples wearing matching shirts, except one solo moviegoer sits alone somewhere in the row. Every couple to the left of that solo person sits in an (even, odd) seat pair: (0, 1), (2, 3), (4, 5), and so on. Because the solo person takes just one seat, every couple to their right gets bumped one seat over into (odd, even) seats! That pattern — whether indices are even or odd — is called index parity.
Why do simpler approaches fall short? Walking down the row pair by pair, using a hash map of counts, or combining every value with bitwise XOR (a binary operation written ^ where two identical numbers cancel out to 0, leaving the unpaired number) all inspect up to n elements and take O(n) time. To meet the O(log n) time limit, we cannot even read most of the list; instead, we use binary search (repeatedly cutting the remaining search interval in half) by peeking at an even seat mid and its right neighbor mid + 1 to see whether the bump has happened yet.
Let's walk through a 5-element slice of Example 1, nums = [4, 4, 6, 9, 9]:
index: 0 1 2 3 4
nums: [4, 4, 6, 9, 9]
1. Window [left=0, right=4]: mid = 2 (even).
Compare nums[2]=6 and nums[3]=9 -> different!
The bump happened at or before index 2, so shrink right = 2.
2. Window [left=0, right=2]: mid = 1 (odd -> step back to even mid = 0).
Compare nums[0]=4 and nums[1]=4 -> equal!
Pair (0, 1) is intact, so jump past it: left = 0 + 2 = 2.
3. Now left == right == 2 -> return nums[2] = 6.
Complexity
- Time:
O(log n), wherenislen(nums). There are(n + 1) // 2even indices in the array, and each iteration discards about half of the remaining even indices while doingO(1)work (one midpoint calculation and one neighbor comparison), taking at most aboutlog2(n)iterations. - Space:
O(1)auxiliary space. We store only three integer indices (left,right, andmid) regardless of how largenumsgrows, without copying or slicing the input list.
Edge cases
- Single-element array (
[7]or[0]):left = 0andright = 0from the beginning, so thewhile left < rightloop runs zero times and immediately returnsnums[0]. - Unpaired element at index
0([1, 5, 5, 9, 9]): Every even-index check seesnums[mid] != nums[mid + 1], pullingrightall the way down to0and returningnums[0]. - Unpaired element at the last index (
[0, 0, 5, 5, 19]): Every check sees an intact pair and advancesleft = mid + 2untilleft == right == len(nums) - 1. Becausemid < rightand both are even,mid + 1is at mostlen(nums) - 2and never causes anIndexError. - Zero values (
[0, 5, 5]or Example 2[0, 0, 5, 5, ...]): Constraints allow0 <= nums[i] <= 10^5; since we compare values directly with==rather than truthiness,0behaves like any other integer.
Common mistakes
- Comparing
nums[mid]andnums[mid + 1]without makingmideven first: At an odd index,nums[mid] == nums[mid + 1]means the opposite (an(odd, even)pair means the shift already happened!). Skippingif mid % 2 == 1: mid -= 1breaks inputs like[0, 0, 5, 5, 8, 12, 12], returning5instead of8. - Advancing
left = mid + 1instead ofleft = mid + 2: Bothnums[mid]andnums[mid + 1]belong to the intact pair, somid + 1cannot be the lone value. Worse, settingleft = mid + 1makesleftodd, somid - 1can fall belowleftand cause an infinite loop on[4, 4, 6]. - Setting
right = mid - 2(ormid - 1) in theelsebranch: Whennums[mid] != nums[mid + 1],nums[mid]itself might be the unpaired value (as in[4, 4, 6, 9, 9]atmid = 2). Droppingmidthrows away the answer! - Using
while left <= rightwithright = mid: Onceleft == right, settingright = midstops shrinking the window, causing an infinite loop or readingnums[mid + 1]past the end of the array.
Alternative approaches
- Partner-index XOR trick (
mid ^ 1): Flipping the lowest bit of any index (mid ^ 1) turns even2kinto2k + 1and odd2k + 1into2k. Comparingnums[mid] == nums[mid ^ 1]lets you updateleft = mid + 1orright = midwithout forcingmidto be even first, in the sameO(log n)time andO(1)space, though it is trickier to explain under interview pressure. - Binary search over pair numbers
kin[0, len(nums) // 2]: Instead of array indices, search pair slotkand comparenums[2 * k]againstnums[2 * k + 1]. This is the exact same algorithm with evenness baked directly into2 * k.
Follow-up questions
- How would you solve the problem if the input list were unsorted? Without sorted order, equal numbers can sit anywhere in the array, so index parity carries no information and sublinear binary search is impossible. Instead, fold every integer together using bitwise XOR (
acc ^= xinitialized to0): matching copies cancel (a ^ a == 0), isolating the unpaired number inO(n)time andO(1)auxiliary space — optimal because leaving even one element unread could miss the answer. - How can you still achieve logarithmic time if every repeated number appears in triples rather than pairs? When repeated numbers form contiguous groups of
3in a sorted array, every intact triple prior to the lone value starts at an index divisible by3(0, 3, 6, ...), whereas the lone value shifts all later triples forward by1. Binary search over group slotsgin[0, len(nums) // 3]and testnums[3 * g] == nums[3 * g + 1]: equality proves the triple starting at3 * gis still aligned so we setleft = g + 1, while inequality proves the shift occurred at or before3 * gso we setright = g, returningnums[3 * left]inO(log n)time andO(1)space. - What if that solo value were duplicated while a different pair lost one copy — or, conversely, every element appeared once except for a single pair? Under the first reading, the sorted array still contains one value of frequency
1and all other values of frequency2, so our exact binary search finds the new singleton without changing a line of code! Under the converse setup — every element appears once except one duplicate pair in a sorted array — arbitrary integers (such as[2, 5, 9, 9, 14]) require anO(n)adjacent-neighbor scan because inspectingnums[mid]gives no directional clue about which side holds the duplicate, unless values come from a dense range like1..n - 1where binary search can comparenums[mid]againstmid + 1.
Follow-up questions
- How would you solve the problem if the input list were unsorted?
- How can you still achieve logarithmic time if every repeated number appears in triples rather than pairs?
- What if that solo value were duplicated while a different pair lost one copy — or, conversely, every element appeared once except for a single pair?
Similar questions
- Best Single-Trade Stock Gain
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
More Xiaohongshu interview questions
- Best Single-Trade Stock Gain Medium