TypeScript: Find Common Elements in Two Arrays

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

1. Introduction

Finding common elements between two arrays is a frequently encountered problem. The solution can vary based on the requirements. Some approaches are brute-force, which can be inefficient with larger arrays, while others use data structures to optimize the search time.

2. Program Overview

We will use a Set data structure in TypeScript to efficiently find the common elements between two arrays. By doing this, we can achieve this with a time complexity of O(n + m), where 'n' and 'm' are the lengths of the two arrays respectively.

3. Code Program

// Function to find the common elements between two arrays
function findCommonElements(arr1: number[], arr2: number[]): number[] {
    const set1 = new Set(arr1);
    const commonElements = [];

    for (let num of arr2) {
        if (set1.has(num)) {
            commonElements.push(num);
            set1.delete(num);  // Ensure unique common elements
        }
    }

    return commonElements;
}

// Test the function
const array1 = [1, 2, 3, 4, 5];
const array2 = [4, 5, 6, 7, 8];
const result = findCommonElements(array1, array2);
console.log(`Common elements are: ${result}`);

4. Step By Step Explanation

1. We start by converting the first array (arr1) into a Set (set1). A Set in TypeScript (and JavaScript) is a collection of values where each value must be unique. This also gives us the advantage of the has method which allows for O(1) lookup time to check if a value exists in the set.

2. We initialize an empty array commonElements which will hold the common numbers between the two arrays.

3. We then loop through each number in the second array (arr2):

  • If the number exists in our Set (set1), it means it's a common element. So, we add it to our commonElements array.
  • We then remove the number from the Set (set1) to ensure that the common numbers in our result are unique.

4. After the loop, we return the commonElements array which contains the common numbers between the two input arrays.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare