A Common-Sense Guide to Data Structures and Algorithms, Second Edition: Time Complexity for Intersection Function (page 93)

@jaywengrow

I have noticed a mistake regarding the best-case scenario time complexity for the intersection function described on p. 92/93:

function intersection(firstArray, secondArray) {
let result = [];
for (let i = 0; i < firstArray.length; i++) {
for (let j = 0; j < secondArray.length; j++) {
if (firstArray[i] === secondArray[j]) {
result.push(firstArray[i]);
break;
}
}
}
return result;
}

In the case of a best-case scenario, i.e. with two arrays being identical, the parapgrah says we’d only have to perform N comparisons.

But when you have two identical arrays, e.g. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], the inner loop would still have to start at index 0 for every value of the outer loop. So when the outer loop reaches the number 10, the inner loop would still have to compare this number 10 with 1, 2, 3, 4, 5, 6, 7, 8, 9 before it gets to the number 10. So I figured the number of comparisons would be calculated as follows:
1 + 2 + 3 + … + (N-1) comparisons, which is approximately N² / 2 comparisons

Therefore, the time complexity should be O(N² / 2) instead of O(N).