5 Best Ways to Find the Smallest Intersecting Element of Each Row in a Python Matrix

Rate this post

πŸ’‘ Problem Formulation: Given a matrix where each row is a set of numbers, the task is to identify the smallest element that is common to all rows (intersecting element). For instance, given a matrix [[1, 2, 3], [4, 3, 2], [2, 5, 6]], the smallest intersecting element for each row is 2.

Method 1: Using Set Intersection

The first method to find the smallest intersecting element utilizes set intersection. We convert each row of the matrix to a set, then perform an intersection operation on these sets. The smallest element of the resulting intersection set gives us the desired output. This method is easy to implement and understand.

Here’s an example:

def find_smallest_intersection(matrix):
    intersection_set = set(matrix[0])
    for row in matrix[1:]:
        intersection_set &= set(row)
    return min(intersection_set) if intersection_set else None

matrix = [[1, 2, 3], [4, 3, 2], [2, 5, 6]]

Output: 2

This code snippet defines a function called find_smallest_intersection() which takes a matrix and returns the smallest intersecting element. We initialize the intersection by converting the first row to a set and then iteratively intersect it with sets made from the other rows. Finally, we return the smallest element in the intersection or None if there is no intersection.

Method 2: Using Python’s Counter

In this approach, we use Python’s Counter class from the collections module to count the frequency of each element across all rows. The smallest element with a frequency equal to the number of rows will be our result. This method is particularly efficient if the matrix is large.

Here’s an example:

from collections import Counter

def smallest_common_element(matrix):
    element_counter = Counter()
    for row in matrix:
    common_elements = [element for element, count in element_counter.items() if count == len(matrix)]
    return min(common_elements) if common_elements else None

matrix = [[1, 2, 3], [4, 3, 2], [2, 5, 6]]

Output: 2

The function smallest_common_element() employs a Counter to tally the occurrence of each element. It iterates over each row to update the counter and then filters out the elements that appear in every row. The smallest of these is returned, provided the list of common elements is not empty.

Method 3: Using List Comprehensions and Set Operations

This method combines list comprehensions with set operations to achieve our goal. It’s concise and takes advantage of Python’s ability to both filter and process collections in a single expression. This is most suitable for small to medium-sized matrices.

Here’s an example:

def smallest_common_element_lc(matrix):
    return min(set.intersection(*map(set, matrix))) if matrix else None

matrix = [[1, 2, 3], [4, 3, 2], [2, 5, 6]]

Output: 2

This snippet defines a function smallest_common_element_lc() that takes a matrix and returns the smallest common element using list comprehension and the built-in min() function. The map() function applies set() to each row, and *operator unpacks the list of sets, allowing us to find the intersection in one go. The result is concise and efficient.

Method 4: Brute Force Approach

Though not the most efficient, the brute force method is a straightforward approach. It involves checking each element of the first row against all other rows and selecting the smallest common element. This approach provides a simple solution but can be impractical for larger datasets due to its time complexity.

Here’s an example:

def brute_force_smallest_common_element(matrix):
    first_row = matrix[0]
    for element in sorted(first_row):
        if all(element in row for row in matrix):
            return element
    return None

matrix = [[1, 2, 3], [4, 3, 2], [2, 5, 6]]

Output: 2

The function brute_force_smallest_common_element() takes a matrix as input and iterates through each element in the sorted first row. It checks if the current element is present in all other rows using a generator expression before returning it if true. If no common element is found, it returns None.

Bonus One-Liner Method 5: Using Functional Programming

For the functional programming enthusiasts, a one-liner solution provides both elegance and compact code using Python’s functional programming features like map() and reduce().

Here’s an example:

from functools import reduce
matrix = [[1, 2, 3], [4, 3, 2], [2, 5, 6]]
print(reduce(set.intersection, map(set, matrix)))

Output: {2}

In this concise one-liner, the reduce() function is used to apply the set.intersection function cumulatively to the sets of all matrix rows. It starts with the first set and iteratively intersects it with subsequent sets, leaving us with the set of common elements, from which the smallest can be extracted.


  • Method 1: Using Set Intersection. Straightforward implementation. May not be the most efficient with large datasets.
  • Method 2: Using Python’s Counter. Handles large matrices well. Requires additional processing to filter common elements.
  • Method 3: Using List Comprehensions and Set Operations. Elegant and concise. Best for small to medium-sized matrices.
  • Method 4: Brute Force Approach. Simplest to understand but inefficient, especially for large matrices.
  • Method 5: Using Functional Programming. A concise one-liner approach. Suits those who prefer functional programming paradigms.