Rewrite the function for it to have O(n) time complexity. Add explanations (±300 words)
const n = 1000;
const array1 = [];
const array2 = [];
for(let i=0;i<n;i++) {
array1.push(Math.round(Math.random() * n));
array2.push(Math.round(Math.random() * n));
}
const intersection = []; // here we store the result
for (let i = 0; i < array1.length; i++) {
for (let j = 0; j < array2.length; j++) {
if (array1[i] === array2[j]) {
intersection.push(array1[i]);
}