Convert the given Matrix into a difference Matrix
Given an input matrix mat[][] of size m*m and the task is to convert the given matrix into a difference matrix of the same size (matrix does not contain any 0 in it) as the input matrix by using the below-mentioned formula:
difference[i][j] = Total Even Numbers in ith Row – Total Odd Numbers in jth Column.
Examples:
Input: {{1, 2, 21, 12}, {4, 5, 6, 18}, {7, 32, 8, 9}, {2, 4, 5, 8}}
Output:
0 1 0 1
1 2 1 2
0 1 0 1
1 2 1 2
Explanation: The input matrix is of 4*4 size and by considering the formula for the difference matrix will be of same size as input matrix, the values for difference matrix will be calculated as:
- difference[0][0] = 2 (total even numbers in 1st row are 2 i.e. 2 and 12) – 2 (total odd numbers in 1st column are 2 i.e. 1 and 7) = 0 .
- difference[0][1] = 2 (total even numbers in 1st row are 2 i.e. 2 and 12) – 1 (there is only one odd number in 2nd column i.e. 5) = 1 .
- difference[0][2] = 2 (total even numbers in 1st row are 2 i.e. 2 and 12) – 2 (total odd numbers in 3rd column are 2 i.e. 21 and 5) = 0 .
- difference[0][3] = 2 (total even numbers in 1st row are 2 i.e. 2 and 12) – 2 (there is only one odd number in 4th column i.e. 9) = 1 .
Same logic for the remaining cells.
Input: {{4, 2, 6}, {5, 8, 23}, {2, 20, 18}}
Output:
2 3 2
0 1 0
2 3 2
Explanation: The input matrix is of 3*3 size and by considering the formula for the difference matrix will be of same size as input matrix, the values for difference matrix will be calculated as:
- difference[0][0] = 3 (total even numbers in 1st row are 3 i.e. 4, 2, 6) – 1 (there is only one odd number in 1st column i.e. 5) = 2 .
- difference[0][1] = 3 (total even numbers in 1st row are 3 ) – 0 (there is no odd number in 2nd column ) = 3 .
- difference[0][2] = 3 (total even numbers in 1st row are 3 i.e. 4, 2, 6) – 1 (there is only one odd number in 3rd column i.e. 23) = 2 .
Same logic for the remaining cells.
Approach: To solve the problem follow the below idea:
The problem can be solved using two dummy arrays, one for maintaining the track of even numbers in every row and another for maintaining the track of odd numbers in every column and use these two arrays in formula for generating difference array.
Below are the steps for the above approach:
- Initialize a matrix say, diff of size m*m (size of input matrix), and initialize two vectors with value 0, rowEven of size m for maintaining the count of even numbers in every row and colOdd of size m for maintaining the count of odd numbers in every column.
- Iterate over the input matrix and if the current element is even then increasing the respective index’s value in the rowEven array else increase the respective index’s value in the colOdd array.
- Iterate over the diff[][] matrix and update every value in the diff[][] matrix by diff[i][j] = rowEven[i] – colOdd[j].
Below code is the code for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector<vector< int > >
findDiffMatrix(vector<vector< int > > matrix)
{
int m = matrix.size();
vector<vector< int > > diff(m, vector< int >(m));
vector< int > rowEven(m, 0);
vector< int > colOdd(m, 0);
for ( int i = 0; i < m; i++) {
for ( int j = 0; j < m; j++) {
if (matrix[i][j] % 2) {
colOdd[j]++;
}
else {
rowEven[i]++;
}
}
}
for ( int i = 0; i < m; i++) {
for ( int j = 0; j < m; j++) {
diff[i][j] = rowEven[i] - colOdd[j];
}
}
return diff;
}
int main()
{
vector<vector< int > > matrix
= { { 4, 2, 6 }, { 5, 8, 23 }, { 2, 20, 18 } };
vector<vector< int > > differenceMatrix
= findDiffMatrix(matrix);
for ( int i = 0; i < differenceMatrix.size(); i++) {
for ( int j = 0; j < differenceMatrix[0].size();
j++) {
cout << differenceMatrix[i][j] << " " ;
}
cout << endl;
}
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class Main {
static ArrayList<ArrayList<Integer> >
findDiffMatrix(ArrayList<ArrayList<Integer> > matrix)
{
int m = matrix.size();
ArrayList<ArrayList<Integer> > diff
= new ArrayList<ArrayList<Integer> >(m);
ArrayList<Integer> rowEven
= new ArrayList<Integer>(m);
ArrayList<Integer> colOdd
= new ArrayList<Integer>(m);
for ( int i = 0 ; i < m; i++) {
ArrayList<Integer> v = new ArrayList<Integer>();
for ( int j = 0 ; j < m; j++)
v.add( 0 );
diff.add(v);
rowEven.add( 0 );
colOdd.add( 0 );
}
for ( int i = 0 ; i < m; i++) {
for ( int j = 0 ; j < m; j++) {
if (matrix.get(i).get(j) % 2 == 1 ) {
colOdd.set(j, colOdd.get(j) + 1 );
}
else {
rowEven.set(i, rowEven.get(i) + 1 );
}
}
}
for ( int i = 0 ; i < m; i++) {
for ( int j = 0 ; j < m; j++) {
diff.get(i).set(j, rowEven.get(i)
- colOdd.get(j));
}
}
return diff;
}
public static void main(String[] args)
{
ArrayList<ArrayList<Integer> > matrix
= new ArrayList<ArrayList<Integer> >();
ArrayList<Integer> v1 = new ArrayList<Integer>(
Arrays.asList( 4 , 2 , 6 ));
ArrayList<Integer> v2 = new ArrayList<Integer>(
Arrays.asList( 5 , 8 , 23 ));
ArrayList<Integer> v3 = new ArrayList<Integer>(
Arrays.asList( 2 , 20 , 18 ));
matrix.add(v1);
matrix.add(v2);
matrix.add(v3);
ArrayList<ArrayList<Integer> > differenceMatrix
= findDiffMatrix(matrix);
for ( int i = 0 ; i < differenceMatrix.size(); i++) {
for ( int j = 0 ;
j < differenceMatrix.get( 0 ).size(); j++) {
System.out.print(
differenceMatrix.get(i).get(j) + " " );
}
System.out.println();
}
}
}
|
Python3
def findDiffMatrix(matrix):
m = len (matrix)
diff = [[ 0 for i in range (m)] for j in range (m)]
rowEven = [ 0 for i in range (m)]
colOdd = [ 0 for i in range (m)]
for i in range (m):
for j in range (m):
if matrix[i][j] % 2 :
colOdd[j] + = 1
else :
rowEven[i] + = 1
for i in range (m):
for j in range (m):
diff[i][j] = rowEven[i] - colOdd[j]
return diff
if __name__ = = '__main__' :
matrix = [[ 4 , 2 , 6 ], [ 5 , 8 , 23 ], [ 2 , 20 , 18 ]]
differenceMatrix = findDiffMatrix(matrix)
for i in range ( len (differenceMatrix)):
for j in range ( len (differenceMatrix[ 0 ])):
print (differenceMatrix[i][j], end = ' ' )
print ()
|
C#
using System;
using System.Collections.Generic;
class Program {
static List<List< int >> FindDiffMatrix(List<List< int >> matrix) {
int m = matrix.Count;
List<List< int >> diff = new List<List< int >>();
for ( int i = 0; i < m; i++) {
diff.Add( new List< int >());
for ( int j = 0; j < m; j++) {
diff[i].Add(0);
}
}
int [] rowEven = new int [m];
int [] colOdd = new int [m];
for ( int i = 0; i < m; i++) {
for ( int j = 0; j < m; j++) {
if (matrix[i][j] % 2 == 1) {
colOdd[j]++;
}
else {
rowEven[i]++;
}
}
}
for ( int i = 0; i < m; i++) {
for ( int j = 0; j < m; j++) {
diff[i][j] = rowEven[i] - colOdd[j];
}
}
return diff;
}
static void Main() {
List<List< int >> matrix = new List<List< int >> {
new List< int > {4, 2, 6},
new List< int > {5, 8, 23},
new List< int > {2, 20, 18}
};
List<List< int >> differenceMatrix = FindDiffMatrix(matrix);
for ( int i = 0; i < differenceMatrix.Count; i++) {
for ( int j = 0; j < differenceMatrix[0].Count; j++) {
Console.Write(differenceMatrix[i][j] + " " );
}
Console.WriteLine();
}
}
}
|
Javascript
function findDiffMatrix(matrix) {
const m = matrix.length;
const diff = new Array(m).fill().map(() => new Array(m).fill(0));
const rowEven = new Array(m).fill(0);
const colOdd = new Array(m).fill(0);
for (let i = 0; i < m; i++) {
for (let j = 0; j < m; j++) {
if (matrix[i][j] % 2 === 1) {
colOdd[j]++;
}
else {
rowEven[i]++;
}
}
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < m; j++) {
diff[i][j] = rowEven[i] - colOdd[j];
}
}
return diff;
}
const matrix = [
[4, 2, 6],
[5, 8, 23],
[2, 20, 18]
];
const differenceMatrix = findDiffMatrix(matrix);
for (let i = 0; i < differenceMatrix.length; i++) {
console.log(differenceMatrix[i].join( " " ));
}
|
Time Complexity: O(2*(m*m)), for traversing the matrix twice, one for finding even and odd numbers and then populating the difference matrix
Auxiliary Space: O(2m + m*m) //2m for two arrays for maintaining even and odd count and m*m for difference matrix.
Another Approach:
To solve the problem follow the below idea:
calculates the difference matrix directly by iterating over the input matrix and calculating the count of even elements in each row and the count of odd elements in each column up to and including the current element. Then calculates the difference for each element and stores it in the corresponding position in the output matrix.
Below are the steps for above approach:
- Initialize an empty matrix, diff, of the same size as the input matrix.
- Iterate over the input matrix row by row.
- For each row, iterate over the elements in the row.
- For each element, calculate the number of even elements in the current row up to and including the current element, and the number of odd elements in the current column up to and including the current element.
- Calculate the difference by subtracting the count of odd elements in the current column from the count of even elements in the current row.
- Store the difference in the corresponding position in the diff matrix.
- Return the diff matrix as the output.
Below code is the code for the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
vector<vector< int >> generate_difference_matrix(vector<vector< int >> matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
vector<vector< int >> diff(rows, vector< int >(cols, 0));
vector< int > row_even_counts(rows, 0);
vector< int > col_odd_counts(cols, 0);
for ( int i = 0; i < rows; i++) {
for ( int j = 0; j < cols; j++) {
if (matrix[i][j] % 2 == 0) {
row_even_counts[i]++;
}
if (matrix[i][j] % 2 == 1) {
col_odd_counts[j]++;
}
}
}
for ( int i = 0; i < rows; i++) {
for ( int j = 0; j < cols; j++) {
diff[i][j] = row_even_counts[i] - col_odd_counts[j];
}
}
return diff;
}
int main() {
vector<vector< int >> matrix {{4, 2, 6}, {5, 8, 23}, {2, 20, 18}};
vector<vector< int >> diff_matrix = generate_difference_matrix(matrix);
for ( auto row : diff_matrix) {
for ( auto val : row) {
cout << val << " " ;
}
cout << endl;
}
return 0;
}
|
Java
import java.util.ArrayList;
public class Main {
static ArrayList<ArrayList<Integer>> generateDifferenceMatrix(ArrayList<ArrayList<Integer>> matrix) {
int rows = matrix.size();
int cols = matrix.get( 0 ).size();
ArrayList<ArrayList<Integer>> diff = new ArrayList<>();
for ( int i = 0 ; i < rows; i++) {
ArrayList<Integer> row = new ArrayList<>();
for ( int j = 0 ; j < cols; j++) {
row.add( 0 );
}
diff.add(row);
}
ArrayList<Integer> rowEvenCounts = new ArrayList<>();
ArrayList<Integer> colOddCounts = new ArrayList<>();
for ( int i = 0 ; i < rows; i++) {
rowEvenCounts.add( 0 );
}
for ( int i = 0 ; i < cols; i++) {
colOddCounts.add( 0 );
}
for ( int i = 0 ; i < rows; i++) {
for ( int j = 0 ; j < cols; j++) {
if (matrix.get(i).get(j) % 2 == 0 ) {
rowEvenCounts.set(i, rowEvenCounts.get(i) + 1 );
}
if (matrix.get(i).get(j) % 2 == 1 ) {
colOddCounts.set(j, colOddCounts.get(j) + 1 );
}
}
}
for ( int i = 0 ; i < rows; i++) {
for ( int j = 0 ; j < cols; j++) {
diff.get(i).set(j, rowEvenCounts.get(i) - colOddCounts.get(j));
}
}
return diff;
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> matrix = new ArrayList<>();
matrix.add( new ArrayList<Integer>() {{add( 4 ); add( 2 ); add( 6 );}});
matrix.add( new ArrayList<Integer>() {{add( 5 ); add( 8 ); add( 23 );}});
matrix.add( new ArrayList<Integer>() {{add( 2 ); add( 20 ); add( 18 );}});
ArrayList<ArrayList<Integer>> diffMatrix = generateDifferenceMatrix(matrix);
for (ArrayList<Integer> row : diffMatrix) {
for ( int val : row) {
System.out.print(val + " " );
}
System.out.println();
}
}
}
|
Python3
def generate_difference_matrix(matrix):
rows = len (matrix)
cols = len (matrix[ 0 ])
diff = [[ 0 for j in range (cols)] for i in range (rows)]
row_even_counts = [ 0 ] * rows
col_odd_counts = [ 0 ] * cols
for i in range (rows):
for j in range (cols):
if matrix[i][j] % 2 = = 0 :
row_even_counts[i] + = 1
if matrix[i][j] % 2 = = 1 :
col_odd_counts[j] + = 1
for i in range (rows):
for j in range (cols):
diff[i][j] = row_even_counts[i] - col_odd_counts[j]
return diff
matrix = [[ 4 , 2 , 6 ], [ 5 , 8 , 23 ], [ 2 , 20 , 18 ]]
diff_matrix = generate_difference_matrix(matrix)
for row in diff_matrix:
for val in row:
print (val, end = ' ' )
print ()
|
C#
using System;
using System.Collections.Generic;
public class MainClass {
static List<List< int > >
GenerateDifferenceMatrix(List<List< int > > matrix)
{
int rows = matrix.Count;
int cols = matrix[0].Count;
List<List< int > > diff = new List<List< int > >();
for ( int i = 0; i < rows; i++) {
List< int > row = new List< int >();
for ( int j = 0; j < cols; j++) {
row.Add(0);
}
diff.Add(row);
}
List< int > rowEvenCounts = new List< int >();
List< int > colOddCounts = new List< int >();
for ( int i = 0; i < rows; i++) {
rowEvenCounts.Add(0);
}
for ( int i = 0; i < cols; i++) {
colOddCounts.Add(0);
}
for ( int i = 0; i < rows; i++) {
for ( int j = 0; j < cols; j++) {
if (matrix[i][j] % 2 == 0) {
rowEvenCounts[i]++;
}
if (matrix[i][j] % 2 == 1) {
colOddCounts[j]++;
}
}
}
for ( int i = 0; i < rows; i++) {
for ( int j = 0; j < cols; j++) {
diff[i][j]
= rowEvenCounts[i] - colOddCounts[j];
}
}
return diff;
}
public static void Main( string [] args)
{
List<List< int > > matrix = new List<List< int > >();
matrix.Add( new List< int >() { 4, 2, 6 });
matrix.Add( new List< int >() { 5, 8, 23 });
matrix.Add( new List< int >() { 2, 20, 18 });
List<List< int > > diffMatrix
= GenerateDifferenceMatrix(matrix);
foreach (List< int > row in diffMatrix)
{
foreach ( int val in row)
{
Console.Write(val + " " );
}
Console.WriteLine();
}
}
}
|
Javascript
function generateDifferenceMatrix(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
const diff = Array.from({ length: rows }, () => Array(cols).fill(0));
const rowEvenCounts = Array(rows).fill(0);
const colOddCounts = Array(cols).fill(0);
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (matrix[i][j] % 2 === 0) {
rowEvenCounts[i]++;
}
if (matrix[i][j] % 2 === 1) {
colOddCounts[j]++;
}
}
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
diff[i][j] = rowEvenCounts[i] - colOddCounts[j];
}
}
return diff;
}
const matrix = [[4, 2, 6], [5, 8, 23], [2, 20, 18]];
const diffMatrix = generateDifferenceMatrix(matrix);
for (const row of diffMatrix) {
for (const val of row) {
process.stdout.write(val + " " );
}
process.stdout.write( "\n" );
}
|
Time Complexity:The time complexity of the code is O(m * n), where m and n are the number of rows and columns in the input matrix, respectively.
Auxiliary Space: O(m * n + m + n), which can be simplified to O(m * n).
Last Updated :
20 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...