Open In App

Find Common Elements in all Rows of a Given Matrix using JavaScript

Last Updated : 26 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Matrix manipulation takes place in a large number of applications, and the detection of shared elements among rows is one of the common challenges.

Example:

Input :  [1, 2, 3],
[2, 3, 4],
[3, 4, 5]

Output: [3]

Input : [1, 2, 3],
[4, 5, 6],
[7, 8, 9]

Output: [ ]

There are the following approaches for finding the common elements in all rows of a given matrix using JavaScript which are as follows:

Using Set Intersection

This method involves comparing sets to find common elements among rows in a matrix. It’s a straightforward method that simplifies the process of identifying shared elements efficiently.

Example: To demonsrtate finding the common elements in all rows of agiven matrix using JavaScript set intersection method.

JavaScript
function findCommonElements(matrix)
 {
    if (matrix.length === 0) return [];

    // Convert first row to set
    let commonSet = new Set(matrix[0]);

    // Intersect with sets of subsequent rows
    for (let i = 1; i < matrix.length; i++) 
    {
        commonSet = new Set(matrix[i]
            .filter(x => commonSet.has(x)));
    }

    return Array
        .from(commonSet);
}

const matrix1 = [
    [1, 2, 3],
    [2, 3, 4],
    [3, 4, 5]
];


console.log(findCommonElements(matrix1));
const matrix2 = 
[
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
console.log(findCommonElements(matrix2));

Output
[ 3 ]
[]

Time Complexity: O(n*m), where n is the number of rows and m is the average number of elements in each row.

Space Complexity: O(m), where m is the average number of elements in each row.

Sorting and Comparing

This method involves sorting the rows of the matrix using sort() method and comparing them to identify common elements using compare() method. It’s a straightforward technique that provides an alternative way to uncover shared elements within the matrix using JavaScript.

Example: To demonsrtate finding the common elements in all rows of a given matrix using Javacript sorting and comparing inbuilt methods.

JavaScript
function findCommonElements(matrix) {
    if (matrix.length === 0) return [];

    // Helper function to find 
    // intersection of two arrays
    const intersect = (arr1, arr2) => {
        let i = 0;
        let j = 0;
        const intersection = [];

        while (i < arr1.length && j < arr2.length)
        {
            if (arr1[i] < arr2[j])
            {
                i++;
            } else if (arr1[i] > arr2[j])
            {
                j++;
            } else {
                intersection.push(arr1[i]);
                i++;
                j++;
            }
        }

        return intersection;
    };

    // Sort each row
    const sortedMatrix = matrix
        .map(row => row.slice()
            .sort((a, b) => a - b));

    // Initialize common elements
    //  with the first row
    let commonElements = sortedMatrix[0];

    // Compare each sorted row
    //  with common elements
    for (let i = 1; i < sortedMatrix.length; i++) 
    {
        commonElements = intersect(commonElements, sortedMatrix[i]);
    }

    return commonElements;
}

const matrix3 =
    [
        [1, 2, 3],
        [2, 3, 4],
        [3, 4, 5]
    ];


console.log(findCommonElements(matrix3));

const matrix4 =
    [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];
console.log(findCommonElements(matrix4));

Output
[ 3 ]
[]

Time Complexity: O(n*m*log m), where n is the number of rows and m is the average number of elements in each row.

Space Complexity: O(n * m), where n is the number of rows and m is the average number of elements in each row.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads