Find distinct elements common to all rows of a matrix in Python

Finding distinct elements common to all rows of a matrix is a useful operation in data analysis. We need to identify elements that appear in every row of the matrix, regardless of their position.

So, if the input matrix is:

13 2 15 4 17
15 3 2 4 36
15 2 15 4 12
15 26 4 3 2
2 19 4 22 15

Then the output will be [2, 4, 15], as these elements appear in all rows.

Using Set Intersection

The simplest approach uses set intersection to find common elements ?

def find_common_elements(matrix):
    if not matrix:
        return []
    
    # Convert first row to set
    common_elements = set(matrix[0])
    
    # Intersect with each subsequent row
    for row in matrix[1:]:
        common_elements = common_elements.intersection(set(row))
    
    return sorted(list(common_elements))

# Test with the example matrix
matrix = [
    [13, 2, 15, 4, 17],
    [15, 3, 2, 4, 36],
    [15, 2, 15, 4, 12],
    [15, 26, 4, 3, 2],
    [2, 19, 4, 22, 15]
]

result = find_common_elements(matrix)
print("Common elements:", result)
Common elements: [2, 4, 15]

Using Sorting and Two Pointers

This approach sorts each row and uses pointers to find common elements efficiently ?

def find_common_sorted(matrix):
    if not matrix:
        return []
    
    n = len(matrix)
    
    # Sort each row
    for i in range(n):
        matrix[i].sort()
    
    # Use pointers for each row
    pointers = [0] * n
    common_elements = []
    
    while pointers[0] < len(matrix[0]):
        current_value = matrix[0][pointers[0]]
        is_common = True
        
        # Check if current value exists in all other rows
        for i in range(1, n):
            # Move pointer to find current_value or next larger element
            while (pointers[i] < len(matrix[i]) and 
                   matrix[i][pointers[i]] < current_value):
                pointers[i] += 1
            
            # Check if we found the value
            if (pointers[i] >= len(matrix[i]) or 
                matrix[i][pointers[i]] != current_value):
                is_common = False
                break
        
        # Add to result if found in all rows
        if is_common:
            common_elements.append(current_value)
            # Move all pointers past this element
            for i in range(n):
                while (pointers[i] < len(matrix[i]) and 
                       matrix[i][pointers[i]] == current_value):
                    pointers[i] += 1
        else:
            pointers[0] += 1
    
    return common_elements

# Test with the example matrix
matrix = [
    [13, 2, 15, 4, 17],
    [15, 3, 2, 4, 36],
    [15, 2, 15, 4, 12],
    [15, 26, 4, 3, 2],
    [2, 19, 4, 22, 15]
]

result = find_common_sorted(matrix)
print("Common elements:", result)
Common elements: [2, 4, 15]

Comparison

Method Time Complexity Space Complexity Best For
Set Intersection O(n × m) O(m) Small matrices, readable code
Sorting + Pointers O(n × m × log m) O(1) Memory-efficient, large matrices

Conclusion

Use set intersection for simple and readable code when working with smaller matrices. The sorting approach is more memory-efficient for larger datasets where space optimization is important.

Updated on: 2026-03-25T09:36:39+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements