878161. Column Sum in a Matrix

Easy

Column Sum in a Matrix

Slug: column-sum-in-a-matrix

Difficulty: Easy

Id: 878161

Topic Tags: Arrays, Matrix

Company Tags: None

Summary

Given a matrix (2D array), calculate the sum of each column. This problem involves arrays and matrices, which are fundamental data structures in computer science.

Detailed Explanation

The given problem is straightforward. We just need to iterate over each column and add up all its elements. Here's the step-by-step breakdown:

  1. Initialize an integer array columnSums with a size equal to the number of columns in the matrix.
  2. Iterate over each row in the matrix.
  3. For each row, iterate over each element (or cell).
  4. Add the current cell value to the corresponding column sum in the columnSums array.
  5. After processing all cells, return the columnSums array.

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(n) as we are storing the sum of each column separately.

Optimized Solutions

Java

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

DevExCode

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

© 2026 DevExCode. All rights reserved.