540. Single Element in a Sorted Array
Intuition
Complexity
Space Complexity
Time Complexity
Code
public int singleNonDuplicate(int[] nums) {
int left = 0, right = nums.length - 1;
// If array has only one element
if (right == 0) return nums[0];
while (left <= right) {
int mid = (left + right) >> 1;
// Check if nums[mid] is the unique element
boolean isDifferentFromLeft = (mid - 1 < 0) || (nums[mid] != nums[mid - 1]);
boolean isDifferentFromRight = (mid + 1 >= nums.length) || (nums[mid] != nums[mid + 1]);
if (isDifferentFromLeft && isDifferentFromRight) {
return nums[mid];
}
boolean isMidIndexOdd = (mid % 2 == 1);
// Check if left side is valid (correct pairing)
if ((isMidIndexOdd && nums[mid] == nums[mid - 1]) || (!isMidIndexOdd && nums[mid] == nums[mid + 1])) {
left = mid + 1; // Unique element must be on the right
} else {
right = mid - 1; // Unique element must be on the left
}
}
return -1; // Should never reach here for a valid input
}
Last updated