Convert the given Matrix into a difference Matrix
Last Updated :
20 Jul, 2023
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
// matrix for storing answer
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++) {
// Printing the output received
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
// for storing answer
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++)
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 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));
matrix.add(v1);
matrix.add(v2);
matrix.add(v3);
// 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++) {
// Printing the output received
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
# matrix for storing answer
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])):
# Printing the output received
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++) {
diff.Add(new List<int>());
for (int j = 0; j < m; j++) {
diff[i].Add(0);
}
}
// 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++) {
// Printing the output received
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(" "));
}
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();
// 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++) {
row.add(0);
}
diff.add(row);
}
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++) {
rowEvenCounts.add(0);
}
for (int i = 0; i < cols; i++) {
colOddCounts.add(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.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<>();
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);
// 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++) {
row.Add(0);
}
diff.Add(row);
}
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++) {
rowEvenCounts.Add(0);
}
for (int i = 0; i < cols; i++) {
colOddCounts.Add(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) {
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();
}
}
}
JavaScript
function generateDifferenceMatrix(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
// create a new matrix of size rows x cols with all elements initialized to 0
const diff = Array.from({ length: rows }, () => Array(cols).fill(0));
const rowEvenCounts = Array(rows).fill(0);
const colOddCounts = Array(cols).fill(0);
// count the number of even numbers in each row and odd numbers in each column
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]++;
}
}
}
// generate the difference matrix using the row and column counts
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);
// print the difference 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).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem