Algo-Sim › Binary Search

Single Element in a Sorted Array

Medium · Binary Search · step through it in Java, Python and C++ on your own input

Every value appears twice except one. Pairs start at even indices before it and odd ones after it, so compare nums[mid] with nums[mid ^ 1].

Problem

The sorted array nums contains every value exactly twice, except for one value that appears once. Return that value in O(log n) time and O(1) extra space.

Constraints

Edge cases to test

Follow-up questions

What if the array is not sorted?
XOR every value: pairs cancel and the single one remains (LC 136), O(n) time, O(1) space.
Why does mid ^ 1 work?
It is mid’s partner index (even ↔ odd). Before the single value pairs start at even indices, after it at odd ones, so a matching partner says the single is to the right.

Solution

Java

public int singleNonDuplicate(int[] nums) {
    int lo = 0, hi = nums.length - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] == nums[mid ^ 1]) lo = mid + 1;
        else hi = mid;
    }
    return nums[lo];
}

Python

def single_non_duplicate(nums):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if nums[mid] == nums[mid ^ 1]: lo = mid + 1
        else: hi = mid
    return nums[lo]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int singleNonDuplicate(vector<int> &nums) {
        int lo = 0, hi = nums.size() - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] == nums[mid ^ 1]) lo = mid + 1;
            else hi = mid;
        }
        return nums[lo];
    }
};

More Binary Search problems