Single Element in a Sorted Array

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.

Return the single element that appears only once.

Your solution must run in O(log n) time and O(1) space.

Example 1:

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

Example 2:

Input: nums = [3,3,7,7,10,11,11] Output: 10

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 105

Solution

Observe that the parity (even or odd) of indices ties closely with where the single element is. We know that the numbers come in pairs before and after the one single element s. For the pairs that is to the left of s: the first element takes an even index e (as array is 0 indexed) and the second element takes an odd index e+1. Then the single element s takes only one position (even), so that the pattern on the right of s is reversed. For the pairs that is to the right of s: the first element takes an odd index o, and the second element takes an even index o+1

Therefore, for an even index e, nums[e]!=nums[e+1] if the s is to the left of o. Similar for an odd index o, nums[o]!=nums[o-1] means s has already appeared. We must also keep an eye out for out of bounds, that is, to check whether idx is the last index in nums.

Implementation

def singleNonDuplicate(self, nums):
    def to_the_left(idx):
        if (idx == len(nums)-1):
            return True
        elif (idx % 2):   # odd
            return nums[idx] != nums[idx-1]
        else:             # even
            return nums[idx] != nums[idx+1]
    
    left, right, ans = 0, len(nums)-1, -1
    while left <= right:
        mid = (left + right) // 2
        if to_the_left(mid):
            ans = mid
            right = mid - 1
        else:
            left = mid + 1
        
    return nums[ans]  

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

In a binary min heap, the minimum element can be found in:


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More