Find Distinct Elements Common to All Rows of a Matrix in Python



Suppose we have a square matrix of order m x m; we have to find all the distinct elements common to all rows of the given matrix.

So, if the input is like

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]

To solve this, we will follow these steps −

  • Define a function sortRows() . This will take matrix

  • n := count of rows

  • for i in range 0 to n, do

    • sort the list matrix[i]

  • In the main method, do the following −

  • n := count of rows

  • sortRows(matrix)

  • current_idx := a list of size n, fill with 0

  • for i in range 0 to n, do

    • current_idx[i] := 0

  • f := 0

  • while current_idx[0] < n, do

    • value := matrix[0, current_idx[0]]

    • present := True

    • for i in range 1 to n, do

      • while (current_idx[i] < n and matrix[i][current_idx[i]] <= value, do

        • current_idx[i] := current_idx[i] + 1

      • if matrix[i, current_idx[i] - 1] is not same as value, then

        • present := False

      • if current_idx[i] is same as n, then

        • f := 1

        • come out from the loop

    • if present is non-zero, then

      • display value

    • if f is same as 1, then

      • come out from the loop

    • current_idx[0] := current_idx[0] + 1

Example

Let us see the following implementation to get better understanding −

 Live Demo

MAX = 100
def sortRows(matrix):
   n = len(matrix)
   for i in range(0, n):
      matrix[i].sort();
def find_common(matrix):
   n = len(matrix)
   sortRows(matrix)
   current_idx = [0] * n
   for i in range (0, n):
      current_idx[i] = 0
   f = 0
   while(current_idx[0] < n):
      value = matrix[0][current_idx[0]]
      present = True
      for i in range (1, n):
         while (current_idx[i] < n and matrix[i][current_idx[i]] <= value):
            current_idx[i] = current_idx[i] + 1
         if (matrix[i][current_idx[i] - 1] != value):
            present = False
         if (current_idx[i] == n):
            f = 1
            break
      if (present):
         print(value, end = ", ")
      if (f == 1):
         break
      current_idx[0] = current_idx[0] + 1

mat = [
   [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]]
find_common(mat)

Input

[[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]]

Output

2, 4, 15,
Updated on: 2020-08-25T09:07:56+05:30

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements