Find the Duplicate in a sequence of 1 to n with size n+1

Kunal Sing

Sep 12, 2024

/* 
* For a series of 1 - n with size n + 1, find the duplicate item in the series
* [1,2,3,4,5,3] -> 3
* [1,2,3,4,1] -> 1
*/


function getDuplicate(arr){
const sum = ((arr.length - 1) * (arr.length))/2
let diff = 0;

for(let i = 0 ; i < arr.length ; i++) {
diff = diff - arr[i];

}
let duplicate = sum + diff;
return Math.abs(duplicate); // gives back the duplicate element
}
+

Check my latest Blog Post

How to Publish Your First npm Package: Creating Rainbow Highlight with Utilities

Read Now
Oh My Gawwdd!!!!!!!

Wow you have been viewing my site since 20 seconds!

+
+