NeetCode #272LC-540MediumBinary Search
← Back to All Problems#272 · #540 · Single Element in a Sorted Array(有序数组中的单一元素)
📌 Problem Statement & Constraints
You are given a sorted array of integers where every element appears exactly twice except one element which appears once. Return the single element. Constraints:
1 <= nums.length <= 10^5, nums.length is odd, 0 <= nums[i] <= 10^5. The solution must run in O(log n) time and O(1) space.💡 Core Algorithmic Approaches
- In a paired array, elements at even indices start a pair. Once the single element is passed, the parity flips.
- Binary search while keeping
midat an even index: ifnums[mid] == nums[mid+1], the single element is to the right; otherwise it is at or to the left ofmid. - Normalising
midto an even index is what keeps the pairing alignment valid throughout the search. - The loop converges on the index of the single element.
💻 Benchmark Python3 Implementation
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if mid % 2 == 1: # keep mid at an even index
mid -= 1
if nums[mid] == nums[mid + 1]:
lo = mid + 2 # the single element is to the right
else:
hi = mid # it is at or left of mid
return nums[lo]
# XOR variant: O(n) time but O(1) space and one line
class Solution2:
def singleNonDuplicate(self, nums: List[int]) -> int:
res = 0
for x in nums:
res ^= x
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log n) for the binary search; O(n) for the XOR variant.
💾 Space Complexity
O(1) for both.
⚠️ Interview Pitfalls & Follow-ups
- Not normalising
midto an even index: the pairing parity would be wrong and the search direction inverted. - Using
lo = mid + 1on a match: the pair spans two indices, so the next candidate ismid + 2. - Using the XOR variant: it is O(n), which the O(log n) requirement forbids (though it is a good sanity check).
- Assuming the array is 0-indexed with pairs starting at 0: this holds because the array length is odd and all other elements are paired.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
有序数组中的单一元素
给你一个仅由整数组成的有序数组,其中每个元素都会出现两次,唯有一个数只会出现一次。请你找出并返回只出现一次的那个数。你设计的解决方案必须满足 O(log n) 时间复杂度和 O(1) 空间复杂度。约束:1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^5;nums 中只有一个数出现一次,其余都出现两次。
核心要点
- 利用下标的奇偶性二分(标准解) :在只出现一次的元素 之前 ,成对元素的下标是 (偶数, 奇数) ; 之后 则变成 (奇数, 偶数) 。
- 保证 mid 为偶数 :若 mid 是奇数则减一,使其指向一对中的第一个位置。
- 判定 :若 nums[mid] == nums[mid+1] ,说明 mid 之前的所有元素都成对(缺失元素在右侧),令 l = mid + 2 ;否则缺失元素在 mid 或左侧,令 r = mid 。
- 结束状态 : l == r 即为答案位置。
常见陷阱
- 不调整 mid 的奇偶性 :直接用 nums[mid] == nums[mid+1] 判断,当 mid 为奇数时语义相反,会得到错误方向。
- l = mid + 1 而非 mid + 2 :该对完整,说明缺失元素在 mid+2 之后,直接跳过整对。
- r = mid − 1 而非 mid : nums[mid] != nums[mid+1] 时,缺失元素可能是 nums[mid] 本身,不能排除。
- 循环条件写成 l <= r :用 l < r ,结束时 l == r 即答案位置。
- 用异或求答案 : reduce(xor, nums) 是 O(n),虽然代码极短但不满足 O(log n) 的要求。
参考实现
class Solution:
def singleNonDuplicate(self, nums: list[int]) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) // 2
if mid % 2 == 1: # 保证 mid 为偶数(成对中的第一个)
mid -= 1
if nums[mid] == nums[mid + 1]:
l = mid + 2 # 该对完整 -> 缺失元素在右侧
else:
r = mid # 该对不完整 -> 缺失元素在 mid 或左侧
return nums[l]