Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.
My code:
function firstDuplicate($a) { $unique = array_unique($a); foreach ($a as $key => $val) { if ($unique[$key] !== $val){ return $key; }else{ return -1; } } }
The code above will be OK when the input is [2, 4, 3, 5, 1]
but if the input is [2, 1, 3, 5, 3, 2]
the output is wrong. The second duplicate occurrence has a smaller index. The expected output should be 3.
How can I fix my code to output the correct result?
Advertisement
Answer
$arr = array(2,1,3,5,3,2); function firstDuplicate($a) { $res = -1; for ($i = count($a); $i >= 1; --$i) { for ($j = 0; $j < $i; ++$j) { if ($a[$j] === $a[$i]) { $res = $a[$j]; } } } return $res; } var_dump(firstDuplicate($arr));
By traversing the array backwards, you will overwrite any previous duplicates with the new, lower-indexed one.
Note: this returns the value (not index), unless no duplicate is found. In that case, it returns -1.