HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Duplicates in array elements and sorting

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortingelementsarrayandduplicates

Problem

I've been given this little test exercise for an interview as php developer, and I'd like to hear from you if my solution is good (enough) or if the problem could have been solved in a better way. Please keep in mind that I've no academic training in CS or equivalent (rather the opposite) and my career started as a self-taught developer.

Given the array:

$numbers = array(
   1,  68,86, 52, 35, 86, 1, 24, 13, 72, 1
);


Take the duplicates and print them out in a string separated by a comma (ex. "a,b,c,d"), ordered in ascendent way.

$holder = [];  // holder for the duplicates
$prev = 0; // previous number
sort($numbers); // sorted them now, so the loop is one-time only

foreach($numbers as $num) {
   if ($prev == $num) {
      $holder[$num] = $num;
      /*I put the $num as index of the array so any double occurrence will overwrite any similar one, to avoid dupes on the $holder that would have compelled me to scan it again.*/
   }
   $prev = $num;  // assign the current number so on the next iteration
                  // i will compare with the next
}

echo implode(',', $holder); //print them out comma separated


I'm not sure if this is an optimal way or could be optimized / made better further. I'm guessing it's an \$O(n)\$ algorithm but again, I admit I have poor theoretical knowledge...

EDIT

My mistake, the requirements were for results sorted, I'm sorry for not pointing it out (I thought I did)

Solution

Since it's an interview, they're probably looking for one of two things:

  • You show that you understand logic



  • You know PHP



It's never advisable to "recreate the wheel", and PHP has built-in methods to do what you're looking for - for example:

// Count how many times each array value occurs in the array
$occurrences = array_count_values($numbers);
// Filter out any that aren't duplicates
$duplicates = array_filter($occurrences, function($count) { return $count > 1; });
// Format the output as requested
$output = implode(',', array_keys($duplicates));


I note you don't say you have a requirement to sort anything, so don't bother.

If I were hiring you I'd obviously prefer you had both of the points above, but I'd rather that you used PHP to its ability as much as possible. Aside from that, this is a code review site, so the same answer would stand in that case. Example.

Code Snippets

// Count how many times each array value occurs in the array
$occurrences = array_count_values($numbers);
// Filter out any that aren't duplicates
$duplicates = array_filter($occurrences, function($count) { return $count > 1; });
// Format the output as requested
$output = implode(',', array_keys($duplicates));

Context

StackExchange Code Review Q#129295, answer score: 5

Revisions (0)

No revisions yet.