Given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once, find this single element that appears only once.
You must implement a solution with a linear runtime complexity and use only constant extra space.
def singleNonDuplicate(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = left + (right - left) // 2
# Ensuring we are always at the start of a pair
if mid % 2 == 1:
mid -= 1
if nums[mid] == nums[mid + 1]:
left = mid + 2
else:
right = mid
return nums[left]
0, 2, 4, ...
) and their other element at the next odd index (1, 3, 5, ...
).left
at 0
and right
at length of nums - 1
.mid
index.mid
is always the start of a pair by making mid
even, if it’s odd then decrement it by 1.mid
is the same as the element at mid + 1
:
left
to mid + 2
.right
to mid
.left
equals right
, that index will hold the single element.This ensures that the solution is both efficient and within the constraints specified.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?