Single Element in a Sorted Array — LeetCode 540 Python Solution

MediumArrayBinary Search
Problem
#540
Reading time
2 min

The problem

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.

Example

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

Python solution

Python
class Solution:
    def singleNonDuplicate(self, nums: List[int]) -> int:
        l, r = 0, len(nums) - 1
        while l < r:
            mid = (l + r) >> 1
            if nums[mid] != nums[mid ^ 1]:
                r = mid
            else:
                l = mid + 1
        return nums[l]

Complexity

MeasureComplexity
Time\textit{O}(\log n), where n is the length of the array \textit{nums}
Space\textit{O}(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 540. Single Element in a Sorted Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 540. Single Element in a Sorted Array?
LeetCode 540. Single Element in a Sorted Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 540. Single Element in a Sorted Array?
The Python solution on this page runs in \textit{O}(\log n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 540. Single Element in a Sorted Array?
The Python solution on this page uses \textit{O}(1) auxiliary space.
What topics does LeetCode 540. Single Element in a Sorted Array cover?
LeetCode 540. Single Element in a Sorted Array is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview