DEV Community

Discussion on: A common coding interview question

Collapse
 
dwilmer profile image
Daan Wilmer
function findIntersection($numbersAsStrings) {
    // parse the strings into numbers
    $numbersAsArrays = array_map(function($string) {
        return explode(', ', $string);
    }, $numbersAsStrings);

    // find the intersections
    $intersection = array_intersect(...$numbersAsArrays);

    // if empty, return string "false"; otherwise, return the numbers as a string
    if (empty($intersection)) {
        return 'false';
    } else {
        return implode(', ', $intersection);
    }
}

because I'd argue that letting your language work for you, and therefore optimizing developer time, is better than optimizing execution time when not strictly necessary.

Collapse
 
elisabethgross profile image
elisabethgross

When the language solves the problem for you... touché

Collapse
 
dwilmer profile image
Daan Wilmer

To follow up: I made three versions of this code. The first version is as above, the second version has the naive approach to finding the intersection:

// find the intersections
$arrA = $numbersAsArrays[0];
$arrB = $numbersAsArrays[1];
$intersection = [];
foreach ($arrA as $num) {
    if (in_array($num, $arrB)) {
        $intersection[] = $num;
    }
}

and a third approach uses a map for lookup:

// find the intersections
$mapA = array_combine($numbersAsArrays[0], $numbersAsArrays[0]);
$mapB = array_combine($numbersAsArrays[1], $numbersAsArrays[1]);

$intersection = [];
foreach ($mapA as $num) {
    if (isset($mapB[$num])) {
        $intersection[] = $num;
    }
}

Performing some timed tests shows that using the built-in function consistently takes about two to three times as long as the self-built map-based function, growing at roughly O(n) using a random array of size 1000 and 10000. Only in exceptional cases would I not use the built-in function.
The naive approach, on the other hand, grows with O(n²) and takes significantly longer at larger array sizes. However, with 26ms with an array size of 1000, it depends on the use case whether I would start optimizing this (if this isn't easily replaced with a built-in function).

Collapse
 
elisabethgross profile image
elisabethgross

Nice work!! Always always interesting to test out a language's built in methods and know whats what when it comes to time complexity.