row wise matrix sum

84k
0

Given a matrix with N rows and M columns, find the sum of elements for every row.

Each row contributes one value to the answer. The value for a row equals the addition of all elements present in the row from left to right.

Example 1

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

Output: [6, 15]

Explanation: First row sum is 1 + 2 + 3 = 6, and second row sum is 4 + 5 + 6 = 15.

Example 2

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

Output: [8, 7, 11]

Explanation: Row sums are 10 + (-2) = 8, 3 + 4 = 7, and 5 + 6 = 11.

Approach

This approach processes the matrix one row at a time. For each row, a running sum is maintained by adding all its elements. Once the row is fully traversed, the computed sum is stored in the result array.

Algorithm

  • Initialize an empty result array to store the sum of each row.

  • Traverse every row using an outer loop.

  • Initialize the sum as 0 for the current row.

  • Traverse all columns of the current row and add each element to the sum.

  • Store the row sum in the result array and return the result after all rows are processed.

Dry Run

row wise sum1

row wise sum1

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to find the sum of every matrix row.
vector<int> rowWiseSum(vector<vector<int>>& mat) {
// Store one sum for every row.
vector<int> result;
int n = mat.size();
int m = mat[0].size();
// Traverse every row from top to bottom.
for (int row = 0; row < n; row++) {
// Store the running sum of the current row.
int sum = 0;
// Traverse every column from left to right.
for (int col = 0; col < m; col++) {
// Add the current row element to the running sum.
sum += mat[row][col];
}
// Store the final sum of the current row.
result.push_back(sum);
}
// Return all row sums.
return result;
}
};
// Driver code.
int main() {
vector<vector<int>> mat = {{1, 2, 3}, {4, 5, 6}};
Solution sol;
vector<int> ans = sol.rowWiseSum(mat);
for (int index = 0; index < (int)ans.size(); index++) {
if (index > 0) {
cout << " ";
}
cout << ans[index];
}
cout << "\n";
return 0;
}

Complexity Analysis

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

Space Complexity: O(N), result array stores one sum for every row.

Interview follow-up Questions

Yes. One loop selects each row, and another loop scans columns inside the selected row.

Arrays

Read Similar Blogs

Comments0