const test1 = [3, 5, 7, 9, 5, 9]
function firstDuplicate(a) {
for (let i of a) {
let posi = Math.abs(i) - 1
if (a[posi] < 0) return posi + 1;
a[posi] = a[posi]* -1 ; (*)
}
return -1
}
// pls explain what does the codeline “a[posi] = a[posi]* -1;” do.
As i’ve known that every statement after statement return
does nothing so why “a[posi] = a[posi]* -1;” appears here.
thanks
The return statement is conditional on the if statement. That is, if (a[posi] < 0) is TRUE, then the function will return. Otherwise, the for loop will continue.