How to find a common element in all rows of a given matrix with sorted rows in Python

2 Answers

0 votes
def find_common_element_in_matrix_rows(matrix):
    from collections import defaultdict

    rows = len(matrix)
    if rows == 0:
        return -1

    cols = len(matrix[0])
    freq = defaultdict(int)

    for row in matrix:
        freq[row[0]] += 1
        for j in range(1, cols):
            if row[j] != row[j - 1]:
                freq[row[j]] += 1

    for key, count in freq.items():
        if count == rows:
            return key

    return -1


matrix = [
    [1, 2, 3, 5, 36],
    [4, 5, 7, 9, 10],
    [5, 6, 8, 9, 18],
    [1, 3, 5, 8, 24]
]

result = find_common_element_in_matrix_rows(matrix)
if result != -1:
    print(f"Common element in all rows: {result}")
else:
    print("No common element found in all rows.")



'''
run:

Common element in all rows: 5

'''

 



answered Oct 3 by avibootz
0 votes
from collections import Counter

def find_common_element(matrix):
    rows = len(matrix)
    if rows == 0:
        return -1

    counter = Counter()

    for row in matrix:
        unique = {row[0]}
        unique.update(val for i, val in enumerate(row[1:], start=1) if val != row[i - 1])
        counter.update(unique)

    return next((num for num, count in counter.items() if count == rows), -1)


matrix = [
    [1, 2, 3, 5, 36],
    [4, 5, 7, 9, 10],
    [5, 6, 8, 9, 18],
    [1, 3, 5, 8, 24]
]

result = find_common_element(matrix)

print(f"Common element in all rows: {result}" if result != -1 else "No common element found in all rows.")



'''
run:

Common element in all rows: 5

'''

 



answered Oct 3 by avibootz
...