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:
- Initialize an integer array
columnSumswith a size equal to the number of columns in the matrix. - Iterate over each row in the matrix.
- For each row, iterate over each element (or cell).
- Add the current cell value to the corresponding column sum in the
columnSumsarray. - After processing all cells, return the
columnSumsarray.
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
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;
}