DEV Community

Discussion on: Find the First Duplicate in a JavaScript Array

Collapse
 
petrasp profile image
Petra Spirkova • Edited

The most comprehensive explanation of the algorithm i've seen so far. Thanks a lot Sean!
The space complexity can indeed be further improved (end of this video: https://www.youtube.com/watch?v=XSdr_O-XVRQ&ab_channel=NickWhite)
const findFirstDuplicate = list => {
for (let i = 0; i < list.length; i++) {
if (list[Math.abs(list[i]) - 1] < 0) {
return Math.abs(list[i]);
} else {
list[Math.abs(list[i]) - 1] = -list[Math.abs(list[i]) - 1];
}
}
return -1;
};