Search for a command to run...
Try your own input
Change the array and replay the algorithm from step one.
Current step
Before the single element, pairs sit on (even, odd) index boundaries. After it, that alignment flips to (odd, even). Testing which side of the flip mid is on tells you which half to discard.
Binary Search on Pair Index
1function singleNonDuplicate(nums) {2 const n = nums.length;//n: 73 4 // Edge cases5 if (n === 1) return nums[0];6 if (nums[0] !== nums[1]) return nums[0];7 if (nums[n - 1] !== nums[n - 2]) return nums[n - 1];8 9 let low = 1, high = n - 2;10 while (low <= high) {11 const mid = Math.floor((low + high) / 2);12 13 // Matches neither neighbour — this is it14 if (nums[mid] !== nums[mid + 1] && nums[mid] !== nums[mid - 1]) {15 return nums[mid];16 }17 18 // Still in the part before the single element19 if ((mid % 2 === 1 && nums[mid] === nums[mid - 1])20 || (mid % 2 === 0 && nums[mid] === nums[mid + 1])) {21 low = mid + 1;22 }23 // Already past it24 else {25 high = mid - 1;26 }27 }28 return -1;29}