Introduction

Greetings, programming enthusiast! In this unit, we're embarking on a thrilling numerical quest, where unidentified bridges connect the islands of data. On these bridges, we'll see hashes and bins, all converging into sets! Throughout our journey, we'll utilize the fundamental concepts of JavaScript arrays and sets to formulate an optimal solution. So, fasten your seatbelt and get ready to solve problems!

Task Statement

The task for this unit is to devise a JavaScript function that accepts two arrays containing unique integers and returns another array containing the elements common to both input arrays. This task provides an intriguing perspective on deriving similarities between two data sequences, a scenario commonly encountered in data comparisons and analytics.

For illustration, suppose we're given two arrays:

const list1 = [1, 2, 3, 5, 8, 13, 21, 34];
const list2 = [2, 3, 5, 7, 13, 21, 31];

The commonElements(list1, list2) function should comb through these arrays of integers and extract the common elements between them.

The expected outcome in this case should be:

JavaScript
const result = [2, 3, 5, 13, 21];
Brute Force Solution and Complexity Analysis

Before we delve into the optimized solution, it is instrumental to consider a basic or naïve approach to this problem and analyze its complexity. Often, our first intuitive approach is to iterate over both arrays in nested loops and find common elements. This way, for each element in the first array, we check for its presence in the second array. If it's found, it is added to our result array. Let's see how such a solution would look:

function commonElementsSlow(list1, list2) {
    const common = [];  // Array to store common elements
    for (let num1 of list1) {
        for (let num2 of list2) {
            if (num1 === num2) {
                common.push(num1);
                break;  // Break inner loop as we found the number in list2
            }
        }
    }
    return common;
}

const list1 = [1, 2, 3, 5, 8, 13, 21, 34];
const list2 = [2, 3, 5, 7, 13, 21, 31];
const result = commonElementsSlow(list1, list2);
console.log(result);  // Prints: [2, 3, 5, 13, 21]

However, the problem with this approach lies in its efficiency. Given that the worst-case scenario has us traversing through every element in both arrays, we refer to this as an O(n * m) solution, where n and m represent the number of elements in list1 and list2, respectively. For large arrays, this iterative approach tends to be inefficient and slow, making it a less desirable solution for this problem.

The solution we aim to implement in the following section utilizes the Set data structure to optimize our algorithm and reach a solution in markedly less computational time.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal