If your
a double loop that solves this problem
breaks out of the loops as soon as a match is found, then both methods are similarly inefficient – they both require iterating over all of N elements M times, worst-case, where N is the length of one array and M is the length of the other. (So, O(n * m)
, or O(n^2)
, depending on how you want to specify the lengths of the inputs.)
The advantage to the second method
two.some(item => one.includes(item))
is that it’s a lot more readable than using for
loops. It’s not more performant – the opposite is true, for
loops are generally faster than array methods.
If you wanted to reduce the complexity to O(n)
, instead of iterating over the second array inside a loop, use a Set lookup inside the loop, which is much faster:
const oneSet = new Set(one);
return two.some(item => oneSet.has(item));
because set lookup is sublinear, and generally O(1) – resulting in an overall complexity of O(n)
.
0
solved Big O for a loop vs a javasccript method that solves a problem [closed]