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, and 14 each appear as adjacent pairs, whereas 6 sits alone at index 2.

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 indices 0..5 before 13 appears once at index 6, followed by (21, 21).

Constraints

  • 1 <= len(nums) <= 10^5 (len(nums) is guaranteed to be odd)
  • 0 <= nums[i] <= 10^5
  • nums is 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 be O(1).

Step-by-step walkthrough

  1. Restate the problem and why O(n) is too slow

    We receive a nondecreasing integer list nums in which every value appears twice, except for one value that appears once. Because nums is sorted, matching duplicates always sit next to each other, and len(nums) is always odd (2k + 1).

    Without a runtime cap, we could walk nums in steps of 2 and 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 all n entries in O(n) time. To meet the O(log n) time and O(1) auxiliary space bounds, we need an O(1) probe near the midpoint that reveals which half holds the unpaired number so we can discard the other half immediately.

  2. 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 2 precede it. 2. At any even index i: - If nums[i] == nums[i + 1], the (even, odd) pair starting at i is still aligned, so the unpaired value must sit strictly to the right (at index i + 2 or higher). - If nums[i] != nums[i + 1], pair alignment is already broken at i, so the unpaired value must sit at i or to its left.

  3. 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): both left and right are even indices, and the unpaired value lies inside nums[left..right].

    Initially, left = 0 is even, and right = len(nums) - 1 is also even because len(nums) is odd. While left < right: 1. Set mid = (left + right) // 2. 2. If mid is odd (mid % 2 == 1), decrement mid by 1 to snap it to the even index right before it. Since left is even and mid >= left, subtracting 1 from an odd mid stays >= left. 3. Why is nums[mid + 1] always in bounds? Both mid and right are even with mid < right, so mid <= right - 2, meaning mid + 1 < right <= len(nums) - 1. 4. Compare nums[mid] with nums[mid + 1]: - Equal -> intact pair at (mid, mid + 1), so advance left = mid + 2 (still even!). - Unequal -> alignment is already broken, so pull right = mid (still even, keeping mid because nums[mid] itself could be the lone number!).

    Once left == right, the window holds a single index, and nums[left] is the answer.

  4. 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] = 6
    

    Now 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] = 13
    
  5. Complete 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), where n is len(nums). There are (n + 1) // 2 even indices in the array, and each iteration discards about half of the remaining even indices while doing O(1) work (one midpoint calculation and one neighbor comparison), taking at most about log2(n) iterations.
  • Space: O(1) auxiliary space. We store only three integer indices (left, right, and mid) regardless of how large nums grows, without copying or slicing the input list.

Edge cases

  • Single-element array ([7] or [0]): left = 0 and right = 0 from the beginning, so the while left < right loop runs zero times and immediately returns nums[0].
  • Unpaired element at index 0 ([1, 5, 5, 9, 9]): Every even-index check sees nums[mid] != nums[mid + 1], pulling right all the way down to 0 and returning nums[0].
  • Unpaired element at the last index ([0, 0, 5, 5, 19]): Every check sees an intact pair and advances left = mid + 2 until left == right == len(nums) - 1. Because mid < right and both are even, mid + 1 is at most len(nums) - 2 and never causes an IndexError.
  • Zero values ([0, 5, 5] or Example 2 [0, 0, 5, 5, ...]): Constraints allow 0 <= nums[i] <= 10^5; since we compare values directly with == rather than truthiness, 0 behaves like any other integer.

Common mistakes

  • Comparing nums[mid] and nums[mid + 1] without making mid even first: At an odd index, nums[mid] == nums[mid + 1] means the opposite (an (odd, even) pair means the shift already happened!). Skipping if mid % 2 == 1: mid -= 1 breaks inputs like [0, 0, 5, 5, 8, 12, 12], returning 5 instead of 8.
  • Advancing left = mid + 1 instead of left = mid + 2: Both nums[mid] and nums[mid + 1] belong to the intact pair, so mid + 1 cannot be the lone value. Worse, setting left = mid + 1 makes left odd, so mid - 1 can fall below left and cause an infinite loop on [4, 4, 6].
  • Setting right = mid - 2 (or mid - 1) in the else branch: When nums[mid] != nums[mid + 1], nums[mid] itself might be the unpaired value (as in [4, 4, 6, 9, 9] at mid = 2). Dropping mid throws away the answer!
  • Using while left <= right with right = mid: Once left == right, setting right = mid stops shrinking the window, causing an infinite loop or reading nums[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 even 2k into 2k + 1 and odd 2k + 1 into 2k. Comparing nums[mid] == nums[mid ^ 1] lets you update left = mid + 1 or right = mid without forcing mid to be even first, in the same O(log n) time and O(1) space, though it is trickier to explain under interview pressure.
  • Binary search over pair numbers k in [0, len(nums) // 2]: Instead of array indices, search pair slot k and compare nums[2 * k] against nums[2 * k + 1]. This is the exact same algorithm with evenness baked directly into 2 * 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 ^= x initialized to 0): matching copies cancel (a ^ a == 0), isolating the unpaired number in O(n) time and O(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 3 in a sorted array, every intact triple prior to the lone value starts at an index divisible by 3 (0, 3, 6, ...), whereas the lone value shifts all later triples forward by 1. Binary search over group slots g in [0, len(nums) // 3] and test nums[3 * g] == nums[3 * g + 1]: equality proves the triple starting at 3 * g is still aligned so we set left = g + 1, while inequality proves the shift occurred at or before 3 * g so we set right = g, returning nums[3 * left] in O(log n) time and O(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 1 and all other values of frequency 2, 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 an O(n) adjacent-neighbor scan because inspecting nums[mid] gives no directional clue about which side holds the duplicate, unless values come from a dense range like 1..n - 1 where binary search can compare nums[mid] against mid + 1.

Follow-up questions

Similar questions

More Xiaohongshu interview questions

All 2 Xiaohongshu questions →