#540
Single Element in a Sorted Array
MediumArrayBinary SearchBinary SearchArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
Using binary search takes advantage of the sorted nature of the array. By leveraging the properties of indices, we can efficiently narrow down the search space to find the unique element in O(log n) time.
⚙️
Algorithm
5 steps- 1Step 1: Initialize left pointer to 0 and right pointer to the last index of the array.
- 2Step 2: While left is less than right, calculate the mid index.
- 3Step 3: Check if mid is even or odd and compare the mid element with its neighbor.
- 4Step 4: If they are the same, move the left pointer to mid + 1; otherwise, move the right pointer to mid.
- 5Step 5: When left equals right, return the element at that index.
solution.py14 lines
1# Full working Python code
2
3def single_non_duplicate(nums):
4 left, right = 0, len(nums) - 1
5 while left < right:
6 mid = left + (right - left) // 2
7 if mid % 2 == 1:
8 mid -= 1
9 if nums[mid] == nums[mid + 1]:
10 left = mid + 2
11 else:
12 right = mid
13 return nums[left]
14ℹ
Complexity note: The time complexity is O(log n) because we are halving the search space with each iteration. The space complexity is O(1) as we are using a constant amount of space.
- 1The array is sorted, which allows for efficient searching methods like binary search.
- 2The unique element's position can be inferred from the properties of pairs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.