Single Element in Sorted Array

Medium Binary SearchArray

Problem

Sorted array where every element appears twice except one which appears once. Return that unique element in O(log n).

Example 1 Input: [1,1,2,3,3,4,4,8,8] Output: 2
Example 2 Input: [3,3,7,7,10,11,11] Output: 10

Constraints

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

class Solution:
    def singleNonDuplicate(self, nums):
        lo, hi = 0, len(nums) - 1
        while lo < hi:
            mid = (lo + hi) // 2
            if mid % 2 == 1:
                mid -= 1
            if nums[mid] == nums[mid + 1]:
                lo = mid + 2
            else:
                hi = mid
        return nums[lo]

Java

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

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Single Element in Sorted Array interactively → ← All solutions