- Related Questions & Answers
- C# program to find common elements in three sorted arrays
- Python program to find common elements in three sorted arrays?
- Java program to find common elements in three sorted arrays
- Find common elements in three sorted arrays in C++
- Find common elements in three sorted arrays by dictionary intersection in Python
- Program to find uncommon elements in two arrays - JavaScript
- Python Program for Find the closest pair from two sorted arrays
- How to find the common elements between two or more arrays in JavaScript?
- Print uncommon elements from two sorted arrays
- How to find common elements between two Arrays using STL in C++?
- C# program to find common elements in three arrays using sets
- Taking common elements from many arrays in JavaScript
- Java Program to Find the closest pair from two sorted arrays
- Merging two sorted arrays into one sorted array using JavaScript
- Find relative complement of two sorted arrays in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We are required to write a JavaScript function that takes in two sorted arrays (both sorted in the same order). The function should prepare and return a third array that contains all those elements that are common to both.

We can easily solve this problem by using two loop in O(m * n) time (m and n being the respective length of the arrays) or even in O(m + n).

But since the arrays are sorted, we can save ourselves time by iterating over the array smaller in size and searching elments in the bigger array using binary search algorithm.

This way, the time complexity of the function will be reduced to O(n * logm) (m > n) which is far better than O(m + n), especially in cases where m >> n

The code for this will be −

const arr1 = [2, 5, 7, 8, 9, 11, 14]; const arr2 = [1, 3, 4, 5, 6, 8, 11, 16]; const binarySearch = (target, arr = []) => { let first = 0; let last = arr.length − 1; let position = −1; let found = false; let middle; while (found === false && first <= last) { middle = Math.floor((first + last)/2); if (arr[middle] == target) { found = true; position = middle; } else if (arr[middle] > target) { last = middle − 1; } else { first = middle + 1; } } return position; } const findCommon = (arr1 = [], arr2 = []) => { const res = []; for (let i = 0; i < arr1.length; ++i){ if (binarySearch(arr1[i], arr2) !== −1){ res.push(arr1[i]); }; }; return res; }; console.log(findCommon(arr1, arr2));

And the output in the console will be −

[5, 8, 11]

Advertisements