Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix.
The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n
Here in the matrix
- M = number of rows in the matrix
- N = number of columns
Example:
Input : M = 3
N = 5
Output: Odd Number Frequency = 9
Even Number Frequency = 6
Input : M = 3
N = 3
{{1, 2, 5},
{6, 7, 9},
{3, 2, 1}}
Output: Odd Number Frequency = 6
Even Number Frequency = 3
Approach
- Initialize two counters as even = 0 & odd = 0
- Traverse through every element present in the matrix and check whether (element % 2 == 0)
- If Yes then increment even++
- Else increment odd++
Below is the implementation of the approach in Java
Java
import java.io.*;
class GFG {
public static void findFreq( int [][] arr, int m, int n)
{
int even = 0 , odd = 0 ;
for ( int i = 0 ; i < m; i++) {
for ( int j = 0 ; j < n; j++) {
if (arr[i][j] % 2 == 0 ) {
even++;
}
else {
odd++;
}
}
}
System.out.println( "Odd Number Frequency: " + odd);
System.out.println( "Even Number Frequency: "
+ even);
}
public static void main(String[] args)
{
int m = 3 , n = 5 ;
int [][] arr = { { 3 , 4 , 5 , 6 , 3 },
{ 4 , 3 , 2 , 7 , 9 },
{ 1 , 5 , 7 , 2 , 4 } };
findFreq(arr, m, n);
}
}
|
OutputOdd Number Frequency: 9
Even Number Frequency: 6
Time Complexity: As the single-dimensional array is traversed it depends on the size of the array over which the operation performs because rest execution either is of the same order or taking some constant space in the memory(variables). Here the traversal is over all the elements of the row and for every row in the matrix. So it depends on the product of rows and columns. Hence, the time complexity is of order(degree)
Space Complexity: Just assigning memory to variables that later gets released with the scope of the variables. As no other auxiliary space is created for the operations to execute. Hence, the space required is constant which is released afterward. 1 is assigned by default hence space complexity is of order 1.
Time Complexity = O(Rows*Columns) or O(m * n)
Space Complexity = O(1)