β Back to Revisions
Day 6
View Problem βMatrix Row and Column Sums
π
October 23, 2025π·οΈ Smart Interviews
Complexity Analysis
Brute Force
O(N*M)
Optimized
O(N*M)
Space
O(M)
Solutions
Pythonπ
import sys
def solve_matrix_sums():
# Set up fast input reading
try:
# Read N and M from the first line
line = sys.stdin.readline().split()
if not line:
return
N = int(line[0])
M = int(line[1])
except:
return
# O(M) Space: Initialize list to store column sums
col_sums = [0] * M
# Store the row sums for separate printing (optional, depends on platform)
row_sums_output = []
# --- Combined Input Pass (O(N*M)) ---
for i in range(N):
try:
# Read the current row's M elements
row_elements = list(map(int, sys.stdin.readline().split()))
except:
break
row_sum = 0
for j in range(M):
element = row_elements[j]
# 1. Row Sum Calculation (Streaming)
row_sum += element
# 2. Column Sum Calculation (Storage)
col_sums[j] += element
# Store Row Sum (for "Matrix Row Sum" output)
row_sums_output.append(row_sum)
# --- Print Row Sums (Output for Problem 1: Matrix Row Sum) ---
for r_sum in row_sums_output:
print(r_sum)
# --- Print Column Sums (Output for Problem 2: Matrix Column Sum) ---
# Note: Added separator for combined testing; remove for individual problem submission.
print("--- Column Sums ---")
for c_sum in col_sums:
print(c_sum)
# If running as a script, solve the problem
if __name__ == "__main__":
solve_matrix_sums()Javaβ
import java.util.ArrayList;
import java.util.Scanner;
class Solution {
public static void solve() {
// Using Scanner for simple input handling
Scanner scanner = new Scanner(System.in);
if (!scanner.hasNextInt()) return;
int N = scanner.nextInt();
if (!scanner.hasNextInt()) return;
int M = scanner.nextInt();
// O(M) Space: Initialize array to store column sums
long[] colSums = new long[M];
// ArrayList to store row sums for the first required output format (Row Sums)
ArrayList<Long> rowSumsOutput = new ArrayList<>();
// --- Combined Input Pass (O(N*M)) ---
for (int i = 0; i < N; i++) {
long rowSum = 0;
for (int j = 0; j < M; j++) {
if (!scanner.hasNextInt()) return;
int element = scanner.nextInt(); // Read the element
// 1. Row Sum Calculation (Streaming)
rowSum += element;
// 2. Column Sum Calculation (Storage)
colSums[j] += element;
}
// Store Row Sum
rowSumsOutput.add(rowSum);
}
// --- Print Row Sums (Output for Problem 1: Matrix Row Sum) ---
for (long sum : rowSumsOutput) {
System.out.println(sum);
}
// --- Print Column Sums (Output for Problem 2: Matrix Column Sum) ---
// Note: Added separator for combined testing; remove for individual problem submission.
System.out.println("--- Column Sums ---");
for (long sum : colSums) {
System.out.println(sum);
}
scanner.close();
}
public static void main(String[] args) {
solve();
}
}C++β‘
#include <iostream>
#include <vector>
using namespace std;
void solve_matrix_sums() {
// Fast I/O is good practice
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int N, M;
// Read N and M
if (!(cin >> N >> M)) return;
// O(M) Space: Initialize vector to store column sums
vector<long long> col_sums(M, 0);
// Vector to store row sums for the first required output format (Row Sums)
vector<long long> row_sums_output;
// --- Combined Input Pass (O(N*M)) ---
for (int i = 0; i < N; ++i) {
long long row_sum = 0;
for (int j = 0; j < M; ++j) {
int element;
if (!(cin >> element)) return; // Read the element
// 1. Row Sum Calculation (Streaming)
row_sum += element;
// 2. Column Sum Calculation (Storage)
col_sums[j] += element;
}
// Store Row Sum
row_sums_output.push_back(row_sum);
}
// --- Print Row Sums (Output for Problem 1: Matrix Row Sum) ---
for (long long sum : row_sums_output) {
cout << sum << "\n";
}
// --- Print Column Sums (Output for Problem 2: Matrix Column Sum) ---
// Note: Added separator for combined testing; remove for individual problem submission.
cout << "--- Column Sums ---\n";
for (long long sum : col_sums) {
cout << sum << "\n";
}
}
int main() {
solve_matrix_sums();
return 0;
}Tags
matrixarraystreaming
π‘ Revision Tips
- β’ Try solving from memory before checking your solution
- β’ Focus on the approach and pattern, not just the code
- β’ Can you explain the solution to someone else?
- β’ Try implementing in a different language