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($arrAas$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($mapAas$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).
I am a full stack engineer, passionate about solving complex problems and collaborating with driven teams! I have 4+ years of experience working at small to mid sized startups.
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:
and a third approach uses a map for lookup:
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).Nice work!! Always always interesting to test out a language's built in methods and know whats what when it comes to time complexity.