GFG App
Open App
Browser
Continue

# 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++

```// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
vector<vector<int> >
findDiffMatrix(vector<vector<int> > matrix)
{
int m = matrix.size();

// Initializing difference
vector<vector<int> > diff(m, vector<int>(m));

// Initializing rowEven array with 0
// for racking even numbers in rows
vector<int> rowEven(m, 0);

// Initializing colOdd array with 0
// for racking odd numbers in columns
vector<int> colOdd(m, 0);
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {

// I current element is odd
// then goto respective index
// in colOdd and increment
// column count
if (matrix[i][j] % 2) {
colOdd[j]++;
}

// Else go to respective index
// in rowEven and increment
// row count
else {
rowEven[i]++;
}
}
}

for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {

// Populating difference
// array as per formula
diff[i][j] = rowEven[i] - colOdd[j];
}
}
return diff;
}

// Drivers code
int main()
{
vector<vector<int> > matrix
= { { 4, 2, 6 }, { 5, 8, 23 }, { 2, 20, 18 } };

// Function call
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

```// Java code for the above approach:

import java.io.*;
import java.util.*;

public class Main {
static ArrayList<ArrayList<Integer> >
findDiffMatrix(ArrayList<ArrayList<Integer> > matrix)
{
int m = matrix.size();

// Initializing difference matrix
ArrayList<ArrayList<Integer> > diff
= new ArrayList<ArrayList<Integer> >(m);

// Initializing rowEven array with 0
// for tracking even numbers in rows
ArrayList<Integer> rowEven
= new ArrayList<Integer>(m);

// Initializing colOdd array with 0
// for tracking odd numbers in columns
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++)
}

for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {

// If current element is odd then
// go to respective index in colOdd
// and increment column count
if (matrix.get(i).get(j) % 2 == 1) {
colOdd.set(j, colOdd.get(j) + 1);
}

// Else go to respective index
// in rowEven and increment row count
else {
rowEven.set(i, rowEven.get(i) + 1);
}
}
}

for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {

// Populating difference array
// as per formula
diff.get(i).set(j, rowEven.get(i)
- colOdd.get(j));
}
}
return diff;
}

// Driver Code
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));

// Function Call
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

```# Python3 code for the above approach

def findDiffMatrix(matrix):
m = len(matrix)
# Initializing difference
diff = [[0 for i in range(m)] for j in range(m)]

# Initializing rowEven array with 0
# for racking even numbers in rows
rowEven = [0 for i in range(m)]

# Initializing colOdd array with 0
# for racking odd numbers in columns
colOdd = [0 for i in range(m)]

for i in range(m):
for j in range(m):

# I current element is odd
# then goto respective index
# in colOdd and increment
# column count
if matrix[i][j] % 2:
colOdd[j] += 1

# Else go to respective index
# in rowEven and increment
# row count
else:
rowEven[i] += 1

for i in range(m):
for j in range(m):

# Populating difference
# array as per formula
diff[i][j] = rowEven[i] - colOdd[j]

return diff

# Drivers code

if __name__ == '__main__':
matrix = [[4, 2, 6], [5, 8, 23], [2, 20, 18]]

# Function call
differenceMatrix = findDiffMatrix(matrix)
for i in range(len(differenceMatrix)):
for j in range(len(differenceMatrix[0])):
print(differenceMatrix[i][j], end=' ')
print()
```

## C#

```// C# code for the above approach

using System;
using System.Collections.Generic;

class Program {
static List<List<int>> FindDiffMatrix(List<List<int>> matrix) {
int m = matrix.Count;

// Initializing difference matrix for storing answer
List<List<int>> diff = new List<List<int>>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
}
}

// Initializing rowEven array with 0 for tracking even numbers in rows
int[] rowEven = new int[m];

// Initializing colOdd array with 0 for tracking odd numbers in columns
int[] colOdd = new int[m];

for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
// If current element is odd then go to respective index in colOdd and increment column count
if (matrix[i][j] % 2 == 1) {
colOdd[j]++;
}
// Else go to respective index in rowEven and increment row count
else {
rowEven[i]++;
}
}
}

for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
// Populating difference array as per formula
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}
};

// Function call
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

```// JavaScript code for the above approach

function findDiffMatrix(matrix) {
const m = matrix.length;

// Initializing difference matrix for storing answer
const diff = new Array(m).fill().map(() => new Array(m).fill(0));

// Initializing rowEven array with 0 for racking even numbers in rows
const rowEven = new Array(m).fill(0);

// Initializing colOdd array with 0 for racking odd numbers in columns
const colOdd = new Array(m).fill(0);

for (let i = 0; i < m; i++) {
for (let j = 0; j < m; j++) {
// If current element is odd then goto
// respective index in colOdd and increment column count
if (matrix[i][j] % 2 === 1) {
colOdd[j]++;
}
// Else go to respective index in rowEven and increment row count
else {
rowEven[i]++;
}
}
}

for (let i = 0; i < m; i++) {
for (let j = 0; j < m; j++) {
// Populating difference array as per formula
diff[i][j] = rowEven[i] - colOdd[j];
}
}

return diff;
}

// Driver code
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(" "));
}
```
Output

```2 3 2
0 1 0
2 3 2 ```

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:

1. Initialize an empty matrix, diff, of the same size as the input matrix.
2. Iterate over the input matrix row by row.
3. For each row, iterate over the elements in the row.
4. 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.
5. Calculate the difference by subtracting the count of odd elements in the current column from the count of even elements in the current row.
6. Store the difference in the corresponding position in the diff matrix.
7. 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();

// create a new matrix of size rows x cols with all elements initialized to 0
vector<vector<int>> diff(rows, vector<int>(cols, 0));

vector<int> row_even_counts(rows, 0);
vector<int> col_odd_counts(cols, 0);

// count the number of even numbers in each row and odd numbers in each column
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]++;
}
}
}

// generate the difference matrix using the row and column counts
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);

// print the difference 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();

// create a new matrix of size rows x cols with all elements initialized to 0
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++) {
}
}

ArrayList<Integer> rowEvenCounts = new ArrayList<>();
ArrayList<Integer> colOddCounts = new ArrayList<>();

// initialize the rowEvenCounts and colOddCounts ArrayLists to 0
for (int i = 0; i < rows; i++) {
}
for (int i = 0; i < cols; i++) {
}

// count the number of even numbers in each row and odd numbers in each column
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);
}
}
}

// generate the difference matrix using the row and column counts
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<>();

ArrayList<ArrayList<Integer>> diffMatrix = generateDifferenceMatrix(matrix);

// print the difference 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

# Count the number of even numbers in each row and odd numbers in each column
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

# Generate the difference matrix using the row and column counts
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)

# print the difference 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;

// create a new matrix of size rows x cols
// with all elements initialized to 0
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++) {
}
}

List<int> rowEvenCounts = new List<int>();
List<int> colOddCounts = new List<int>();

// initialize the rowEvenCounts and
// colOddCounts ArrayLists to 0
for (int i = 0; i < rows; i++) {
}
for (int i = 0; i < cols; i++) {
}

// count the number of even numbers in
// each row and odd numbers in each column
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]++;
}
}
}

// generate the difference matrix using
// the row and column counts
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
diff[i][j]
= rowEvenCounts[i] - colOddCounts[j];
}
}

return diff;
}

// Driver Code
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);

// print the difference matrix
foreach(List<int> row in diffMatrix)
{
foreach(int val in row)
{
Console.Write(val + " ");
}
Console.WriteLine();
}
}
}```
Output

```2 3 2
0 1 0
2 3 2 ```

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).

My Personal Notes arrow_drop_up