Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created April 25, 2023 14:53
Show Gist options
  • Select an option

  • Save optimistiks/cc975b4ac2f185a401ec222bd16ca323 to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/cc975b4ac2f185a401ec222bd16ca323 to your computer and use it in GitHub Desktop.
In this problem, you’re given an array of sorted integers in which all of the integers, except one, appears twice. Your task is to find the single integer that appears only once. The solution should have a time complexity of O(logn) or better and a space complexity of O(1) .
export function singleNonDuplicate(nums) {
let start = 0;
let end = nums.length - 1;
while (start < end) {
let mid = Math.floor((end - start) / 2) + start;
if (mid % 2 !== 0) {
mid -= 1;
}
if (nums[mid] !== nums[mid + 1]) {
end = mid;
} else {
start = mid + 2;
}
}
return nums[start];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment