Created
August 26, 2016 05:00
-
-
Save pzaich/c7e7c9307d9f66a14b246e7f79c67a3f to your computer and use it in GitHub Desktop.
Find duplicates in a sorted array in Olog(n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Find duplicate in sorted array | |
var sortedArray = [1,2,3,3,4,5,6,7,8]; | |
var sortedNoDupes = [1,2,3,,4,5,6,7,8]; | |
// Binary search | |
function findDuplicate(arr) { | |
var midpoint = Math.floor(arr.length / 2); | |
var mid = arr[midpoint]; | |
var left = arr[midpoint - 1]; | |
var right = arr[midpoint + 1]; | |
if (mid === left || mid === right) { | |
return mid; | |
} else { | |
left = findDuplicate(arr.slice(0, midpoint)); | |
right = findDuplicate(arr.slice(midpoint + 1, arr.length)); | |
return left || right; | |
} | |
} | |
console.log(findDuplicate(sortedArray)) | |
console.log(findDuplicate(sortedNoDupes)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment