Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to return the first repeated element of array

Tags:

arrays

php

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?

like image 864
Fero Avatar asked Feb 21 '11 12:02

Fero


People also ask

How do you find the first occurrence of an element in an array?

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.

How do you find the index of repeated elements in an array?

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.


2 Answers

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;
}
like image 55
Haim Evgi Avatar answered Sep 21 '22 12:09

Haim Evgi


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) 
} 
like image 45
kapa Avatar answered Sep 21 '22 12:09

kapa