Created
March 26, 2016 21:05
-
-
Save jinwolf/b1687e8e81848160e809 to your computer and use it in GitHub Desktop.
Find the first duplicate number in the list where the range is 1:n+1 and the size of the array is n that implies there should be at least one duplicate in the list
This file contains hidden or 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
'use strict' | |
var num_list_1 = [3, 4, 2, 3, 1, 5]; | |
var num_list_2 = [3, 1, 2, 2]; | |
var num_list_3 = [4, 3, 1, 1, 4]; | |
function find_duplicate(num_list) { | |
// initializing | |
var slowIndex = num_list.length - 1; | |
var fastIndex = num_list.length - 1; | |
var slow = num_list[slowIndex]; | |
var fast = num_list[fastIndex]; | |
while(true) { | |
// move next | |
slowIndex = slow - 1; | |
slow = num_list[slowIndex]; | |
fastIndex = fast - 1; | |
fast = num_list[fastIndex]; | |
fastIndex = fast - 1; | |
fast = num_list[fastIndex]; | |
// if the values are the same and indices are different this is the duplicate | |
if (slow === fast) { | |
if (slowIndex !== fastIndex) { | |
return slow; | |
} | |
slowIndex = num_list.length - 1; | |
slow = num_list[slowIndex]; | |
while (true) { | |
// move slow point one by one until the values are the same | |
slowIndex = slow - 1; | |
slow = num_list[slowIndex]; | |
fastIndex = fast - 1; | |
fast = num_list[fastIndex]; | |
if (slow === fast) { | |
if (slowIndex !== fastIndex) { | |
return slow; | |
} else { | |
return slowIndex + 1; | |
} | |
} | |
} | |
} | |
} | |
} | |
console.log(find_duplicate(num_list_1)); | |
console.log(find_duplicate(num_list_2)); | |
console.log(find_duplicate(num_list_3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment