Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Finding the Single Non-Duplicate Element in a Sorted Array: A Binary Search
Mar 22, 2025
484 views
Written by Prashant Basnet
👋 Welcome to my Signature, a space between logic and curiosity.
I’m a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and “aha” moments that keep me building.
Situation:
You are given a sorted array of integers where every element appears exactly twice, except for one element that appears only once. Find and return the single element that does not have a duplicate.
Example 2:
Constraints:
Action:
Why Compare Based on Even/Odd Index?
Mid At Even
l m r 0. 1 2. 3. 4. 5. 6. 7. 8 [1, 1, 2, 3 ,3, 4, 4, 8, 8]Mid @ Odd
l. m r 0. 1 2. 3. 4. 5. 6 [3, 3, 5, 5, 6, 7, 7 ]In a sorted array where every element appears exactly twice except for one, the pairs of duplicates will follow a specific pattern:
This pattern allows us to determine whether the single element is on the left or right side of the middle index.
If mid is even:
Our Strategy:
function binarySearch(){ let l = 0, r = nums.length - 1 while (l < r) { let mid = Math.floor((l + r) / 2) if (mid % 2 === 0) { // at even index pair start if (nums[mid] === nums[mid + 1]) { // go right l = mid + 2 } else { // go left r = mid } } else { // at odd index, the pair lies in prev index i.e even if (nums[mid] === nums[mid - 1]) { // we found a pair // go right l = mid + 1 } else { //go left r = mid } } } return nums[l] }This can be simplified here: by adjusting mid to always fall on the mid @ even index
function binarySearch(){ let l = 0, r = nums.length - 1 while(l < r){ let mid = Math.floor((l + r) / 2) if(mid % 2 === 1){ mid-- // mid is always even } if(nums[mid] === nums[mid + 1]){ //go right l = mid + 2 }else{ // go left r = mid } } return nums[l] };