Leetcode 540. Single Element in a Sorted Array
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.
Your solution should run in O(log n) time and O(1) space.
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Input: nums = [3,3,7,7,10,11,11]
Output: 10
Given that the array is sorted and every element except one appears twice, a binary search approach can be utilized to achieve the O(log n) time complexity requirement. Here’s an approach to solve the problem:
left
and right
) to perform binary search on the array.mid
element with its adjacent elements, adjust the left
or right
pointers to narrow down the area where the single element could be located.left
is equal to right
, at which point the position will be located at the single element.public class Solution {
public int singleNonDuplicate(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
// Ensure the mid is even for proper comparison with next element
if (mid % 2 == 1) {
mid--;
}
// Check if this breaks the pair property
if (nums[mid] == nums[mid + 1]) {
// Single element must be on the right side
left = mid + 2;
} else {
// Single element must be on the left side
right = mid;
}
}
// left should be at the single element's position
return nums[left];
}
}
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?