We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Single Element in a Sorted Array

Number: 540

Difficulty: Medium

Paid? No

Companies: Google, Amazon, Bloomberg, Meta, Microsoft, Coupang, Adobe, Apple, Uber, Oracle, Yahoo, Nvidia, Infosys, ServiceNow


Problem Description

Given a sorted array where every element appears exactly twice except for one element that appears only once, find and return the single element. The solution must run in O(log n) time and O(1) space.


Key Insights

  • The array is sorted and identical elements appear as consecutive pairs.
  • Binary search can be used to take advantage of the array's sorted property.
  • Before the single element, the first occurrence of each pair is at an even index.
  • After the single element, this order is disrupted, which helps in adjusting the binary search boundaries.

Space and Time Complexity

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


Solution

We perform a binary search on the array. At every step, we ensure that the mid index used for comparison is even by adjusting it if necessary. If the element at the even index mid is equal to the next element, it indicates that the single element is further to the right. Otherwise, the single element is to the left, including mid. This check is based on the fact that proper pairing before the single element maintains a specific even-index pattern. We continue this approach until the search space narrows down to the single element.


Code Solutions

# Python solution to find the single non-duplicate element in a sorted array

def singleNonDuplicate(nums):
    # Initialize binary search boundaries
    left, right = 0, len(nums) - 1
    
    # Continue the binary search until left meets right
    while left < right:
        # Find the middle index
        mid = left + (right - left) // 2
        
        # Adjust mid to be even for proper pairing comparison
        if mid % 2 == 1:
            mid -= 1
            
        # If the element at mid is equal to its neighbor, the unique element is on the right
        if nums[mid] == nums[mid + 1]:
            left = mid + 2
        else:
            # Otherwise, the unique element is on the left, including mid
            right = mid
    
    # When left equals right, we have found the unique element
    return nums[left]

# Example usage:
# print(singleNonDuplicate([1,1,2,3,3,4,4,8,8]))
← Back to All Questions