878019. Row Sum in a Matrix

Easy

Here is the detailed Markdown blog post for the "Row Sum in a Matrix" problem:

Row Sum in a Matrix

Summary

Given a matrix, find the sum of each row. This problem involves basic array manipulation and no complex algorithms are needed.

Detailed Explanation

The solution to this problem is quite simple. We just need to iterate over each row in the matrix, add up all the elements in that row, and store the result. Here's a step-by-step breakdown:

  • Iterate over each row in the matrix.
  • For each row, initialize a variable row_sum to 0.
  • Iterate over each element in the current row.
  • Add the value of the current element to row_sum.
  • After iterating over all elements in the current row, print or return row_sum.

Here's an ASCII art diagram representing the matrix and the process:

Matrix: [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]

Row Sum Calculation:
  Row 1: 1 + 2 + 3 = 6
  Row 2: 4 + 5 + 6 = 15
  Row 3: 7 + 8 + 9 = 24

Result: [6, 15, 24]

The time complexity of this solution is O(m*n), where m is the number of rows and n is the number of columns in the matrix. The space complexity is O(1) as we only need a constant amount of extra space to store row_sum.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] rowSums(int[][] matrix) {
    int[][] result = new int[matrix.length][];
    for (int i = 0; i < matrix.length; i++) {
        int sum = 0;
        for (int j = 0; j < matrix[i].length; j++) {
            sum += matrix[i][j];
        }
        result[i] = new int[]{sum};
    }
    return result;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.