Skip to content

Commit

Permalink
added floyd cycle detection method
Browse files Browse the repository at this point in the history
  • Loading branch information
Abid Khan committed Feb 1, 2023
1 parent 7b667ba commit 85460d9
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion arrays/basics/findDuplicate.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,44 @@ function findDuplicate2(nums){
}
}

console.log("Actual: ",findDuplicate([1,3,4,2,2]), "Expected",2, findDuplicate([1,3,4,2,2]) == 2 ? "PASSED" : "FAILED", "\n")
console.log("Actual: ",findDuplicate2([1,3,4,2,2]), "Expected",2, findDuplicate2([1,3,4,2,2]) == 2 ? "PASSED" : "FAILED", "\n")


// 1 Using Object

console.log("Approach 2")
function findDuplicate3(nums){
let obj = {};
for(let item of nums){
if(obj[item]){
return item
}else{
obj[item] = 1
}
}
}

// console.log("Actual: ",findDuplicate3([1,3,4,2,2]), "Expected",2, findDuplicate3([1,3,4,2,2]) == 2 ? "PASSED" : "FAILED", "\n")


function findDuplicate4(nums){
let slow = nums[0];
let fast = nums[0];

while(true){
slow = nums[slow];
fast = nums[nums[fast]]
if(slow == fast) break;
}
console.log(slow, fast)
slow = nums[0];
while(slow != fast){

slow = nums[slow]
fast = nums[fast]
}

return fast
}

console.log("Actual: ",findDuplicate4([2, 6, 4, 1, 3, 1, 5]), "Expected",1)

0 comments on commit 85460d9

Please sign in to comment.