even/odd count in matrix

93.3k
0

Given a matrix with N rows and M columns, count the number of even elements and odd elements present in the matrix.

Example 1

Input: mat = [[1, 2, 3], [4, 5, 6]]

Output: Even Count = 3, Odd Count = 3

Explanation: Even elements are 2, 4, 6, and odd elements are 1, 3, 5.

Example 2

Input: mat = [[0, -3], [8, 11], [-6, 5]]

Output: Even Count = 3, Odd Count = 3

Explanation: 0, 8, and -6 are even, while -3, 11, and 5 are odd.

Approach

This approach scans every element of the matrix once. For each element, it checks whether the value is even or odd using the modulo operator and updates the corresponding counter. After the traversal, both counters give the required result.

Algorithm

  • Initialize evenCount and oddCount as 0, where evenCount keeps track of the total even elements and oddCount keeps track of the total odd elements.

  • Traverse every row using an outer loop, which allows each row of the matrix to be accessed one by one.

  • For each row, use an inner loop to traverse all columns, which makes sure every element within that row is processed.

  • If the current element is divisible by 2, it signifies that the element is even, so evenCount is incremented; otherwise, oddCount is incremented.

  • Return both counts after all elements have been processed, as they now represent the total number of even and odd elements in the matrix.

Dry Run

count even odd

count even odd

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to count even and odd elements in a matrix.
pair<int, int> countEvenOdd(vector<vector<int>>& mat) {
// Store the count of even elements.
int evenCount = 0;
// Store the count of odd elements.
int oddCount = 0;
// Traverse every row from top to bottom.
for (int row = 0; row < (int)mat.size(); row++) {
// Traverse every column from left to right.
for (int col = 0; col < (int)mat[row].size(); col++) {
// Check whether the current value is even.
if (mat[row][col] % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
}
// Return even and odd counts together.
return {evenCount, oddCount};
}
};
// Driver code.
int main() {
vector<vector<int>> mat = {{1, 2, 3}, {4, 5, 6}};
Solution sol;
pair<int, int> ans = sol.countEvenOdd(mat);
cout << "Even Count = " << ans.first << ", Odd Count = " << ans.second << "\n";
return 0;
}

Complexity Analysis

Time Complexity: O(N × M), traversal visits every matrix cell exactly once.

Space Complexity: O(1), only two counters and loop variables are used.

Interview follow-up Questions

Yes. Every cell must be checked because each value contributes to one count.

Arrays

Read Similar Blogs

Comments0