Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Python/540.single_element_in_a_sorted_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
540. Single Element in a Sorted Array

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.

Your solution must run in O(log n) time and O(1) space.

Time Complexity: O(log n)
"""



def singleNonDuplicate(self, nums: List[int]) -> int:
l, r = 0, len(nums)-1

while l <= r:
mid = (l+r)//2

if mid==0 or mid==len(nums)-1 or \
(nums[mid] != nums[mid-1] and nums[mid] != nums[mid+1]):
return nums[mid]

if (mid % 2 == 0 and nums[mid] == nums[mid+1]) or \
(mid % 2 == 1 and nums[mid] == nums[mid-1]):
l = mid+1
else:
r = mid-1