This is an interview question:
What is the best way to return the first repeated element out of the array of integers?
Example:
Given an array [12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98]
.
The return value in this case is 12
.
How can this be done?
The idea to solve this problem is iterate on the elements of given array and check given elements in an array and keep track of first and last occurrence of the found element's index. Below are the steps to implement the above idea: Run a for loop and for i = 0 to n-1. Take first = -1 and last = -1.
Given an integer array, find the minimum index of a repeating element in linear time and doing just a single traversal of the array. A naive solution would be to consider each element arr[i] present in the array and search it in subarray arr[i+1…n-1] . We return its index as soon as a duplicate is found.
i think that if you look of performance, foreach loop is the faster
# temp array
$array_help = array();
# run over the array
foreach ($array as $val) {
if (isset($array_help[$val]))
# found if is set already !
return $val;
else
# its the first time this value appear
$array_help[$val] = 1;
}
This will give you all the duplicate values and their original positions:
$diff = array_diff_assoc($array, array_unique($array));
var_dump($diff);
result:
array(3) {
[4]=> int(12)
[9]=> int(83)
[14]=> int(98)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With