← Algorithms
Ep. 01··17:32

540. Single Element in a Sorted Array

MediumBinary SearchBit manipulation
#540 Single Element in a Sorted ArrayYouTube · loads on click (privacy-enhanced mode)

#The idea

Starting index of each pair of duplicated element is even until non duplicate element. For example, 7,7,8,8,10,14,14 pair of 7 starts at 0, pair of 8 starts at 2, but after 10, this pattern changes to odd indices, where pair of 14 starts at 5. This pattern helps us to cut array in half in each iteration. If mid is odd, then elements at mid and mid - 1 are compared, otherwise mid and mid + 1. Based on this equality we either cut left or right sub array. Furthermore, there is one special case, when the element we try to find is located at the end of input array. As length of the array - n is always odd, the last valid index is n - 1 , making mid + 1 index out of range, which leads us to evaluating additional mid == n - 1 condition before equality check.

singleNonDuplicate.pypython
class Solution:
    def singleNonDuplicate(self, nums: List[int]) -> int:
        n, index = len(nums), -1
        left, right = 0, n - 1

        while left <= right:
            mid = (left + right) // 2
            if mid == n - 1 or nums[mid] != nums[mid ^ 1]:
                right = mid - 1
                index = mid
            else:
                left = mid + 1
        
        return nums[index]