Single Element in a Sorted Array

Pattern: Binary search on sorted arrays

medium

Every value appears twice except one. Before the single value, each pair starts at an even index; after it, each pair starts at an odd index. Binary search on even indexes for where the pattern breaks.

The problem

You are given a sorted array in which every value appears exactly twice, except one value that appears once. Return that single value, in O(log n) time and O(1) memory. For example, [1, 1, 2, 3, 3, 4, 4, 8, 8] gives 2 and [3, 3, 7, 7, 10, 11, 11] gives 10.

The function name singleNonDuplicate matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Before the single value, at which kind of index (even or odd) does each pair start?
  • After the single value, what changes?
  • Looking at one even index and its right neighbour, how can you tell which side the single value is on?

Hints

    Brute force, and why it fails

    XOR all values together, since pairs cancel: O(n). Or walk in steps of 2 and find the first broken pair: also O(n). The rule asks for O(log n), and the pairing pattern gives it.

    The key insight

    The single value shifts every later pair by one position. That turns "which value is alone" into a sorted yes/no pattern on even indexes, which binary search can split.

    Dry run

    10lo
    11 
    22 
    33 
    34 
    45 
    46 
    87 
    88hi

    nums = [1, 1, 2, 3, 3, 4, 4, 8, 8]. Pairs before the single value start at even indexes, as 1 1 does at 0.

    Step 1 of 4

    The plan

    lo = 0, hi = n - 1
    while lo < hi:
        mid = lo + (hi - lo) / 2
        if mid is odd: mid = mid - 1
        if nums[mid] == nums[mid + 1]: lo = mid + 2
        else: hi = mid
    return nums[lo]
    

    Complexity

    Time
    O(log n)
    Space
    O(1)

    Each step halves the range of even positions left.

    Edge cases

    • One value: it is the answer.
    • The single value first, [1, 2, 2], or last, [1, 1, 2].
    • The array length is always odd, so mid + 1 never runs past hi.
    I've built my logic, show the code

    Java

    class Solution {
        public int singleNonDuplicate(int[] nums) {
            int lo = 0, hi = nums.length - 1;
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (mid % 2 == 1) mid--;            // look at the start of a pair: an even index
                if (nums[mid] == nums[mid + 1]) lo = mid + 2;   // pairs are intact so far: single is to the right
                else hi = mid;                                  // a pair is broken here: single is at mid or left
            }
            return nums[lo];
        }
    }

    C++

    class Solution {
    public:
        int singleNonDuplicate(vector<int>& nums) {
            int lo = 0, hi = static_cast<int>(nums.size()) - 1;
            while (lo < hi) {
                int mid = lo + (hi - lo) / 2;
                if (mid % 2 == 1) mid--;            // look at the start of a pair: an even index
                if (nums[mid] == nums[mid + 1]) lo = mid + 2;   // pairs are intact so far: single is to the right
                else hi = mid;                                  // a pair is broken here: single is at mid or left
            }
            return nums[lo];
        }
    };

    Python

    class Solution:
        def singleNonDuplicate(self, nums: list[int]) -> int:
            lo, hi = 0, len(nums) - 1
            while lo < hi:
                mid = (lo + hi) // 2
                if mid % 2 == 1:
                    mid -= 1                        # look at the start of a pair: an even index
                if nums[mid] == nums[mid + 1]:
                    lo = mid + 2                    # pairs are intact so far: single is to the right
                else:
                    hi = mid                        # a pair is broken here: single is at mid or left
            return nums[lo]

    Common mistakes

    • Comparing at odd indexes without adjusting, which flips the meaning of the test.
    • Setting lo = mid + 1 after an intact pair, which puts lo on an odd index.
    • Setting hi = mid - 1 when the pair is broken, which can skip the single value at mid.

    Similar problems