Single Element in a Sorted Array

Single Element in a Sorted Array (LeetCode 540): binary search on even indices to find the one non-duplicated element in O(log n).

Problem Statement

In a sorted array where every element appears exactly twice except one, find the single element in O(log n) time and O(1) space.

Example

Input:  nums = [1,1,2,3,3,4,4,8,8]
Output: 2

Approach

Before the single element, pairs start at even indices (nums[even] == nums[even+1]). After it, this breaks. Binary search on even midpoints: if nums[mid] == nums[mid+1] the single element is to the right, else it is at mid or to the left.

Complexity

  • Time: O(log n)
  • Space: O(1)

Solution Code

Python

def singleNonDuplicate(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

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--;
        if (nums[mid] == nums[mid + 1]) lo = mid + 2;
        else hi = mid;
    }
    return nums[lo];
}

C++

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

Key Takeaways

  • Snapping mid to an even index aligns it with the pair pattern.
  • The pairing invariant breaks exactly at the single element.
  • Reference: LeetCode 540 (Single Element in a Sorted Array).
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.