Single Element in a Sorted Array — LeetCode 540 Python Solution
- Problem
- #540
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| 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.