Skip to main content

Find common elements in all rows of a given matrix efficiently

Here given code implementation process.

/*
    Java Program
    Find common elements in all rows of a given matrix efficiently
*/
import java.util.HashMap;

public class DistinctElement
{
    // Display given matrix element
    public void display(int[][] data, int n, int m)
    {   
        int i = 0;
        int j = 0;
        // iterate the loop through by row
        for (i = 0; i < n; ++i)
        {
            // iterate the loop through by col
            for (j = 0; j < m ; ++j) 
            {
                System.out.print("  "+data[i][j]);
            }
            System.out.print("\n");
        }
        System.out.print("\n");
    }
    // Find all common elements in each row
    public void commonElement(int[][] data)
    {
        // Result indicator
        boolean result = false;

        // Get number of rows
        int n = data.length;
        // Get number of columns
        int m = data[0].length;
        
        // Loop controlling variables
        int i = 0;
        int j = 0;

        HashMap <Integer,Integer > record = new HashMap <Integer,Integer> ();
        
        // Display given matrix element
        System.out.print(" Given matrix  : ");

        display(data, n, m);

        System.out.print(" Result element  : ");

        // Get unique records in first row
        for (i = 0; i < m  ; ++i ) 
        {
            if(record.containsKey(data[0][i])==false)
            {
                record.put(data[0][i],1);
            }   
        }

        // iterate the loop through by row
        for (i = 1; i < n ; ++i ) 
        {
            // iterate the loop through by col
            for (j = 0; j < m ; ++j ) 
            {
                if(record.containsKey(data[i][j]) && record.get(data[i][j]) == i)
                {
                    if((i+1)==n)
                    {
                        // When row is last then print element value
                        System.out.print("  "+data[i][j]);
                        // Change result status
                        result = true;
                    }
                    
                    // Change the element frequency
                    record.replace(data[i][j],i+1);  
                }
            }
        }

        
        if (result == false)
        {
            // When no common element
            System.out.print("\n None \n");
        }
        
    }
    public static void main(String[] arg)
    {
        DistinctElement task = new DistinctElement();

        // Matrix elements
        int[][] data = 
        {
            {3,  2,  8,  1,  5},
            {3,  7,  8,  2,  1},
            {2,  4,  3, 14,  1},
            {2,  3, 18,  1, 20}
        };
        
        // Test
        task.commonElement(data);
    }
}

Output

 Given matrix  :   3  2  8  1  5
  3  7  8  2  1
  2  4  3  14  1
  2  3  18  1  20

 Result element  :   2  3  1
// Include header file
#include <iostream>
#include <unordered_map>
#define N 4
#define M 5
using namespace std;

class DistinctElement
{
	public:
		// Display given matrix element
		void display(int data[N][M])
		{
			int i = 0;
			int j = 0;
			// iterate the loop through by row
			for (i = 0; i < N; ++i)
			{
				// iterate the loop through by col
				for (j = 0; j < M; ++j)
				{
					cout << "  " << data[i][j];
				}
				cout << "\n";
			}
			cout << "\n";
		}
	// Find all common elements in each row
	void commonElement(int data[N][M])
	{
		// Result indicator
		bool result = false;
		// Loop controlling variables
		int i = 0;
		int j = 0;
		unordered_map <int,int> record ;
		// Display given matrix element
		cout << " Given matrix  : \n";
		this->display(data);
		cout << " Result element  : ";
		// Get unique records in first row
		for (i = 0; i < M; ++i)
		{
			if (record.find(data[0][i]) != record.end() == false)
			{
				record[data[0][i]] = 1;
			}
		}
		// iterate the loop through by row
		for (i = 1; i < N; ++i)
		{
			// iterate the loop through by col
			for (j = 0; j < M; ++j)
			{
				if (record.find(data[i][j]) != record.end() 
                    && record[data[i][j]] == i)
				{
					if ((i + 1) == N)
					{
						// When row is last then print element value
						cout << "  " << data[i][j];
						// Change result status
						result = true;
					}
					// Change the element frequency
					record[data[i][j]] = i + 1;
				}
			}
		}
		if (result == false)
		{
			// When no common element
			cout << "\n None \n";
		}
	}
};
int main()
{
	DistinctElement task = DistinctElement();
	// Matrix elements
	int data[N][M] = {
		{
			3 , 2 , 8 , 1 , 5
		} , 
      	{
			3 , 7 , 8 , 2 , 1
		} , 
      	{
			2 , 4 , 3 , 14 , 1
		} , 
      	{
			2 , 3 , 18 , 1 , 20
		}
	};
	// Test
	task.commonElement(data);
	return 0;
}

Output

 Given matrix  :
  3  2  8  1  5
  3  7  8  2  1
  2  4  3  14  1
  2  3  18  1  20

 Result element  :   2  3  1
// Include namespace system
/*
    C# Program
    Find common elements in all rows of a given matrix 
    efficiently
*/
using System;
using System.Collections.Generic;
public class DistinctElement
{
	// Display given matrix element
	public void display(int[, ] data, int n, int m)
	{
		int i = 0;
		int j = 0;
		// iterate the loop through by row
		for (i = 0; i < n; ++i)
		{
			// iterate the loop through by col
			for (j = 0; j < m; ++j)
			{
				Console.Write("  " + data[i, j]);
			}
			Console.Write("\n");
		}
		Console.Write("\n");
	}
	// Find all common elements in each row
	public void commonElement(int[, ] data)
	{
		// Result indicator
		Boolean result = false;
		// Get number of rows
		int n = data.GetLength(0);
		// Get number of columns
		int m = data.GetLength(1);
		// Loop controlling variables
		int i = 0;
		int j = 0;
		Dictionary < int, int > record = new Dictionary < int, int > ();
		// Display given matrix element
		Console.Write(" Given matrix  : \n");
		display(data, n, m);
		Console.Write(" Result element  : ");
		// Get unique records in first row
		for (i = 0; i < m; ++i)
		{
			if (record.ContainsKey(data[0, i]) == false)
			{
				record.Add(data[0, i], 1);
			}
		}
		// iterate the loop through by row
		for (i = 1; i < n; ++i)
		{
			// iterate the loop through by col
			for (j = 0; j < m; ++j)
			{
				if (record.ContainsKey(data[i, j]) && record[data[i, j]] == i)
				{
					if ((i + 1) == n)
					{
						// When row is last then print element value
						Console.Write("  " + data[i, j]);
						// Change result status
						result = true;
					}
					// Change the element frequency
					record[data[i, j]] = i + 1;
				}
			}
		}
		if (result == false)
		{
			// When no common element
			Console.Write("\n None \n");
		}
	}
	public static void Main(String[] arg)
	{
		DistinctElement task = new DistinctElement();
		// Matrix elements
		int[, ] data = {
			{
				3 , 2 , 8 , 1 , 5
			} , {
				3 , 7 , 8 , 2 , 1
			} , {
				2 , 4 , 3 , 14 , 1
			} , {
				2 , 3 , 18 , 1 , 20
			}
		};
		// Test
		task.commonElement(data);
	}
}

Output

 Given matrix  :
  3  2  8  1  5
  3  7  8  2  1
  2  4  3  14  1
  2  3  18  1  20

 Result element  :   2  3  1
<?php
/*
    Php Program
    Find common elements in all rows of a given matrix 
    Efficiently
*/
class DistinctElement
{
	// Display given matrix element
	public	function display( & $data, $n, $m)
	{
		$i = 0;
		$j = 0;
		// iterate the loop through by row
		for ($i = 0; $i < $n; ++$i)
		{
			// iterate the loop through by col
			for ($j = 0; $j < $m; ++$j)
			{
				echo "  ". $data[$i][$j];
			}
			echo "\n";
		}
		echo "\n";
	}
	// Find all common elements in each row
	public	function commonElement( & $data)
	{
		// Result indicator
		$result = false;
		// Get number of rows
		$n = count($data);
		// Get number of columns
		$m = count($data[0]);
		// Loop controlling variables
		$i = 0;
		$j = 0; 
      	$record = array();
		// Display given matrix element
		echo " Given matrix  : \n";
		$this->display($data, $n, $m);
		echo " Result element  : ";
		// Get unique records in first row
		for ($i = 0; $i < $m; ++$i)
		{
			if (array_key_exists($data[0][$i], $record) == false)
			{
				$record[$data[0][$i]] = 1;
			}
		}
		// iterate the loop through by row
		for ($i = 1; $i < $n; ++$i)
		{
			// iterate the loop through by col
			for ($j = 0; $j < $m; ++$j)
			{
				if (array_key_exists($data[$i][$j], $record) 
                    && $record[$data[$i][$j]] == $i)
				{
					if (($i + 1) == $n)
					{
						// When row is last then print element value
						echo "  ". $data[$i][$j];
						// Change result status
						$result = true;
					}
					$record[$data[$i][$j]] = $i + 1;
				}
			}
		}
		if ($result == false)
		{
			// When no common element
			echo "\n None \n";
		}
	}
}

function main()
{
	$task = new DistinctElement();
	// Matrix elements
	$data = array(
      array(3, 2, 8, 1, 5), 
      array(3, 7, 8, 2, 1), 
      array(2, 4, 3, 14, 1), 
      array(2, 3, 18, 1, 20)
    );
	// Test
	$task->commonElement($data);
}
main();

Output

 Given matrix  :
  3  2  8  1  5
  3  7  8  2  1
  2  4  3  14  1
  2  3  18  1  20

 Result element  :   2  3  1
/*
    Node Js Program
    Find common elements in all rows of a given matrix 
    Efficiently
*/
class DistinctElement
{
	// Display given matrix element
	display(data, n, m)
	{
		var i = 0;
		var j = 0;
		// iterate the loop through by row
		for (i = 0; i < n; ++i)
		{
			// iterate the loop through by col
			for (j = 0; j < m; ++j)
			{
				process.stdout.write("  " + data[i][j]);
			}
			process.stdout.write("\n");
		}
		process.stdout.write("\n");
	}
	// Find all common elements in each row
	commonElement(data)
	{
		// Result indicator
		var result = false;
		// Get number of rows
		var n = data.length;
		// Get number of columns
		var m = data[0].length;
		// Loop controlling variables
		var i = 0;
		var j = 0; 
		var record = new Map();
		// Display given matrix element
		process.stdout.write(" Given matrix  : \n");
		this.display(data, n, m);
		process.stdout.write(" Result element  : ");
		// Get unique records in first row
		for (i = 0; i < m; ++i)
		{
			if (record.has(data[0][i]) == false)
			{
				record.set(data[0][i], 1);
			}
		}
		// iterate the loop through by row
		for (i = 1; i < n; ++i)
		{
			// iterate the loop through by col
			for (j = 0; j < m; ++j)
			{
				if (record.has(data[i][j]) 
                    && record.get(data[i][j]) == i)
				{
					if ((i + 1) == n)
					{
						// When row is last then print element value
						process.stdout.write("  " + data[i][j]);
						// Change result status
						result = true;
					}
					// Change the element frequency
					record.set(data[i][j], i + 1);
				}
			}
		}
		if (result == false)
		{
			// When no common element
			process.stdout.write("\n None \n");
		}
	}
}

function main()
{
	var task = new DistinctElement();
	// Matrix elements
	var data = [
		[3, 2, 8, 1, 5] , 
        [3, 7, 8, 2, 1] , 
        [2, 4, 3, 14, 1] , 
        [2, 3, 18, 1, 20]
	];
	// Test
	task.commonElement(data);
}
main();

Output

 Given matrix  :
  3  2  8  1  5
  3  7  8  2  1
  2  4  3  14  1
  2  3  18  1  20

 Result element  :   2  3  1
#  Python 3 Program
#  Find common elements in all rows of a given matrix 
#  Efficiently

class DistinctElement :
	#  Display given matrix element
	def display(self, data, n, m) :
		i = 0
		j = 0
		#  iterate the loop through by row
		while (i < n) :
			#  iterate the loop through by col
			while (j < m) :
				print("  ", data[i][j], end = "")
				j += 1
			
			print(end = "\n")
			i += 1
			j = 0
		
		print(end = "\n")
	
	#  Find all common elements in each row
	def commonElement(self, data) :
		#  Result indicator
		result = False
		#  Get number of rows
		n = len(data)
		#  Get number of columns
		m = len(data[0])
		#  Loop controlling variables
		i = 0
		j = 0 
		record = dict()
		#  Display given matrix element
		print(" Given matrix  : ")
		self.display(data, n, m)
		print(" Result element  : ", end = "")
		#  Get unique records in first row
		while (i < m) :
			if ((data[0][i] in record.keys()) == False) :
				record[data[0][i]] = 1
			i += 1
	
		#  iterate the loop through by row
		i = 1
		while (i < n) :
			#  iterate the loop through by col
			while (j < m) :
				if (data[i][j] in record.keys() 
                    and record.get(data[i][j]) == i) :
					if ((i + 1) == n) :
						#  When row is last then print element value
						print("  ", data[i][j], end = "")
						#  Change result status
						result = True
					
					#  Change the element frequency
					record[data[i][j]] = i + 1
				
				j += 1
			
			i += 1
			j = 0
		
		if (result == False) :
			#  When no common element
			print("\n None ")
		
	

def main() :
	task = DistinctElement()
	#  Matrix elements
	data = [
		[3, 2, 8, 1, 5] , 
        [3, 7, 8, 2, 1] , 
        [2, 4, 3, 14, 1] , 
        [2, 3, 18, 1, 20]
	]
	#  Test
	task.commonElement(data)

if __name__ == "__main__": main()

Output

 Given matrix  :
   3   2   8   1   5
   3   7   8   2   1
   2   4   3   14   1
   2   3   18   1   20

 Result element  :    2   3   1
#  Ruby Program
#  Find common elements in all rows of a given matrix 
#  Efficiently

class DistinctElement 
	#  Display given matrix element
	def display(data, n, m) 
		i = 0
		j = 0
		#  iterate the loop through by row
		while (i < n) 
			#  iterate the loop through by col
			while (j < m) 
				print("  ", data[i][j])
				j += 1
			end

			print("\n")
			i += 1
			j = 0
		end

		print("\n")
	end

	#  Find all common elements in each row
	def commonElement(data) 
		#  Result indicator
		result = false
		#  Get number of rows
		n = data.length
		#  Get number of columns
		m = data[0].length
		#  Loop controlling variables
		i = 0
		j = 0 
		record = Hash.new
		#  Display given matrix element
		print(" Given matrix  : \n")
		self.display(data, n, m)
		print(" Result element  : ")
		#  Get unique records in first row
		while (i < m) 
			if (record.key?(data[0][i]) == false) 
				record[data[0][i]] = 1
			end

			i += 1
		end

		#  iterate the loop through by row
		i = 1
		while (i < n) 
			#  iterate the loop through by col
			while (j < m) 
				if (record.key?(data[i][j]) && record[data[i][j]] == i) 
					if ((i + 1) == n) 
						#  When row is last then print element value
						print("  ", data[i][j])
						#  Change result status
						result = true
					end

					record[data[i][j]] = i + 1
				end

				j += 1
			end

			i += 1
			j = 0
		end

		if (result == false) 
			#  When no common element
			print("\n None \n")
		end

	end

end

def main() 
	task = DistinctElement.new()
	#  Matrix elements
	data = [
		[3, 2, 8, 1, 5] , 
        [3, 7, 8, 2, 1] , 
        [2, 4, 3, 14, 1] , 
        [2, 3, 18, 1, 20]
	]
	#  Test
	task.commonElement(data)
end

main()

Output

 Given matrix  : 
  3  2  8  1  5
  3  7  8  2  1
  2  4  3  14  1
  2  3  18  1  20

 Result element  :   2  3  1
import scala.collection.mutable._;
/*
    Scala Program
    Find common elements in all rows of a given matrix 
    Efficiently
*/
class DistinctElement
{
	// Display given matrix element
	def display(data: Array[Array[Int]], n: Int, m: Int): Unit = {
		var i: Int = 0;
		var j: Int = 0;
		// iterate the loop through by row
		while (i < n)
		{
			// iterate the loop through by col
			while (j < m)
			{
				print("  " + data(i)(j));
				j += 1;
			}
			print("\n");
			i += 1;
			j = 0;
		}
		print("\n");
	}
	// Find all common elements in each row
	def commonElement(data: Array[Array[Int]]): Unit = {
		// Result indicator
		var result: Boolean = false;
		// Get number of rows
		var n: Int = data.length;
		// Get number of columns
		var m: Int = data(0).length;
		// Loop controlling variables
		var i: Int = 0;
		var j: Int = 0; 
		var record: Map[Int, Int] = Map();
		// Display given matrix element
		print(" Given matrix  : \n");
		this.display(data, n, m);
		print(" Result element  : ");
		// Get unique records in first row
		while (i < m)
		{
			if (record.contains(data(0)(i)) == false)
			{
				record.addOne(data(0)(i), 1);
			}
			i += 1;
		}
		// iterate the loop through by row
		i = 1;
		while (i < n)
		{
			// iterate the loop through by col
			while (j < m)
			{
				if (record.contains(data(i)(j)) && record.get(data(i)(j)).get == i)
				{
					if ((i + 1) == n)
					{
						// When row is last then print element value
						print("  " + data(i)(j));
						// Change result status
						result = true;
					}
					// Change the element frequency
					record.addOne(data(i)(j), i + 1);
				}
				j += 1;
			}
			i += 1;
			j = 0;
		}
		if (result == false)
		{
			// When no common element
			print("\n None \n");
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: DistinctElement = new DistinctElement();
		// Matrix elements
		var data: Array[Array[Int]] = Array(
          Array(3, 2, 8, 1, 5), 
          Array(3, 7, 8, 2, 1), 
          Array(2, 4, 3, 14, 1), 
          Array(2, 3, 18, 1, 20)
        );
		// Test
		task.commonElement(data);
	}
}

Output

 Given matrix  :
  3  2  8  1  5
  3  7  8  2  1
  2  4  3  14  1
  2  3  18  1  20

 Result element  :   2  3  1
import Foundation
/*
    Swift 4 Program
    Find common elements in all rows of a given matrix 
    Efficiently
*/
class DistinctElement
{
	// Display given matrix element
	func display(_ data: [[Int]], _ n: Int, _ m: Int)
	{
		var i: Int = 0;
		var j: Int = 0;
		// iterate the loop through by row
		while (i < n)
		{
			// iterate the loop through by col
			while (j < m)
			{
				print("  ", data[i][j], terminator: "");
				j += 1;
			}
			print(terminator: "\n");
			i += 1;
			j = 0;
		}
		print(terminator: "\n");
	}
	// Find all common elements in each row
	func commonElement(_ data: [[Int]])
	{
		// Result indicator
		var result: Bool = false;
		// Get number of rows
		let n: Int = data.count;
		// Get number of columns
		let m: Int = data[0].count;
		// Loop controlling variables
		var i: Int = 0;
		var j: Int = 0;
		var record = [Int: Int]();
		// Display given matrix element
		print(" Given matrix  : ");
		self.display(data, n, m);
		print(" Result element  : ", terminator: "");
		// Get unique records in first row
		while (i < m)
		{
			if (record.keys.contains(data[0][i]) == false)
			{
				record[data[0][i]] = 1;
			}
			i += 1;
		}
		// iterate the loop through by row
		i = 1;
		while (i < n)
		{
			// iterate the loop through by col
			while (j < m)
			{
				if (record.keys.contains(data[i][j]) 
                    && record[data[i][j]] == i)
				{
					if ((i + 1) == n)
					{
						// When row is last then print element value
						print("  ", data[i][j], terminator: "");
						// Change result status
						result = true;
					}
					// Change the element frequency
					record[data[i][j]] = i + 1;
				}
				j += 1;
			}
			i += 1;
			j = 0;
		}
		if (result == false)
		{
			// When no common element
			print("\n None ");
		}
	}
}
func main()
{
	let task: DistinctElement = DistinctElement();
	// Matrix elements
	let data: [[Int]] = [
		[3, 2, 8, 1, 5] , 
        [3, 7, 8, 2, 1] , 
        [2, 4, 3, 14, 1] , 
        [2, 3, 18, 1, 20]
	];
	// Test
	task.commonElement(data);
}
main();

Output

 Given matrix  :
   3   2   8   1   5
   3   7   8   2   1
   2   4   3   14   1
   2   3   18   1   20

 Result element  :    2   3   1
/*
    Kotlin Program
    Find common elements in all rows of a given matrix 
    Efficiently
*/
class DistinctElement
{
	// Display given matrix element
	fun display(data: Array < Array < Int >> , n: Int, m: Int): Unit
	{
		var i: Int = 0;
		var j: Int = 0;
		// iterate the loop through by row
		while (i < n)
		{
			// iterate the loop through by col
			while (j < m)
			{
				print("  " + data[i][j]);
				j += 1;
			}
			print("\n");
			i += 1;
			j = 0;
		}
		print("\n");
	}
	// Find all common elements in each row
	fun commonElement(data: Array < Array < Int >> ): Unit
	{
		// Result indicator
		var result: Boolean = false;
		// Get number of rows
		var n: Int = data.count();
		// Get number of columns
		var m: Int = data[0].count();
		// Loop controlling variables
		var i: Int = 0;
		var j: Int = 0; 
		var record = mutableMapOf<Int, Int>();
		// Display given matrix element
		print(" Given matrix  : \n");
		this.display(data, n, m);
		print(" Result element  : ");
		// Get unique records in first row
		while (i < m)
		{
			if (record.containsKey(data[0][i]) == false)
			{
				record.put(data[0][i], 1);
			}
			i += 1;
		}
		// iterate the loop through by row
		i = 1;
		while (i < n)
		{
			// iterate the loop through by col
			while (j < m)
			{
				if (record.containsKey(data[i][j]) 
                    && record.getValue(data[i][j]) == i)
				{
					if ((i + 1) == n)
					{
						// When row is last then print element value
						print("  " + data[i][j]);
						// Change result status
						result = true;
					}
					// Change the element frequency
					record.put(data[i][j], i + 1);
				}
				j += 1;
			}
			i += 1;
			j = 0;
		}
		if (result == false)
		{
			// When no common element
			print("\n None \n");
		}
	}
}
fun main(args: Array <String> ): Unit
{
	var task: DistinctElement = DistinctElement();
	// Matrix elements
	var data: Array < Array <Int>> = arrayOf(
      arrayOf(3, 2, 8, 1, 5), 
      arrayOf(3, 7, 8, 2, 1), 
      arrayOf(2, 4, 3, 14, 1), 
      arrayOf(2, 3, 18, 1, 20)
    );
	// Test
	task.commonElement(data);
}

Output

 Given matrix  :
  3  2  8  1  5
  3  7  8  2  1
  2  4  3  14  1
  2  3  18  1  20

 Result element  :   2  3  1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment