BackhardHeapGoogleAmazon

Matrix Vessel Analyzer 45 Solution

Problem Statement

You are tasked with analyzing a 2D matrix of integers representing a grid of vessels. The goal is to determine the minimum possible value of the maximum row sum and the maximum column sum. Specifically, for a given matrix, compute the sum of each row and the sum of each column. Let R be the maximum row sum and C be the maximum column sum. Your task is to find the minimum value of max(R, C) over all possible configurations of the matrix, but since the matrix is fixed, you simply need to compute max(R, C) for the given matrix. However, to add complexity, you must also consider the heap-based approach to efficiently manage and compare these sums. The problem requires you to use a max-heap to keep track of the largest row and column sums, and then return the maximum of these two values. This ensures that the solution is both efficient and scalable for large matrices.

Input: A 2D array of integers, where each element represents a vessel's capacity. The matrix is guaranteed to be non-empty and rectangular.

Output: A single integer representing the maximum of the largest row sum and the largest column sum.

Example 1
Input
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output
24

Explanation: Row sums: 1+2+3=6, 4+5+6=15, 7+8+9=24. Column sums: 1+4+7=12, 2+5+8=15, 3+6+9=18. Max row sum = 24, max column sum = 18. Result = max(24, 18) = 24.

Example 2
Input
matrix = [[10, 20], [30, 40]]
Output
70

Explanation: Row sums: 10+20=30, 30+40=70. Column sums: 10+30=40, 20+40=60. Max row sum = 70, max column sum = 60. Result = max(70, 60) = 70.

Example 3
Input
matrix = [[5, 5, 5], [5, 5, 5], [5, 5, 5]]
Output
15

Explanation: Row sums: 5+5+5=15 (all rows). Column sums: 5+5+5=15 (all columns). Max row sum = 15, max column sum = 15. Result = max(15, 15) = 15.

Example 4
Input
matrix = [[1, 100], [100, 1]]
Output
101

Explanation: Row sums: 1+100=101, 100+1=101. Column sums: 1+100=101, 100+1=101. Max row sum = 101, max column sum = 101. Result = max(101, 101) = 101.

Constraints

  • 1 <= matrix.length <= 10^3
  • 1 <= matrix[0].length <= 10^3
  • -10^4 <= matrix[i][j] <= 10^4
  • The matrix is guaranteed to be rectangular (all rows have the same length).
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Matrix Vessel Analyzer 45 — Problem Statement & Solution Guide

HeapHardDFS Traversal
TimeO(N·M) initial + O(Q·log(N+M)) for Q updates/queries
|
SpaceO(N+M) for sums and heaps

Problem Description

You are tasked with analyzing a 2D matrix of integers representing a grid of vessels. The goal is to determine the minimum possible value of the maximum row sum and the maximum column sum. Specifically, for a given matrix, compute the sum of each row and the sum of each column. Let R be the maximum row sum and C be the maximum column sum. Your task is to find the minimum value of max(R, C) over all possible configurations of the matrix, but since the matrix is fixed, you simply need to compute max(R, C) for the given matrix. However, to add complexity, you must also consider the heap-based approach to efficiently manage and compare these sums. The problem requires you to use a max-heap to keep track of the largest row and column sums, and then return the maximum of these two values. This ensures that the solution is both efficient and scalable for large matrices.

Input: A 2D array of integers, where each element represents a vessel's capacity. The matrix is guaranteed to be non-empty and rectangular.

Output: A single integer representing the maximum of the largest row sum and the largest column sum.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Matrix Vessel Analyzer 45"

hard

WHY DOES IT MATTER?

Fast max‑queries on mutable aggregates are a common bottleneck in real‑time analytics.

OPTIMIZATION CHALLENGE

Transforming O(N·M) recomputation into O(log N + log M) updates cuts runtime by orders of magnitude.

REAL-WORLD CONNECTION

Think of monitoring server load per rack (rows) and per switch (columns) where each metric updates continuously.

Always pair a mutable aggregate with a priority queue and use lazy deletion to keep the code simple and performant.

COMPLEXITY AT A GLANCE

⏱ Time:O(N·M) initial + O(Q·log(N+M)) for Q updates/queries
💾 Space:O(N+M) for sums and heaps

Core Theory — Why This Approach?

The naive solution recomputes every row and column sum after each modification, leading to O(N·M) per query which is infeasible for large matrices or many updates. By treating row sums and column sums as independent streams, we can maintain two max‑heaps—one for rows and one for columns—so the current maximum can be retrieved in O(1) and updated in O(log N) or O(log M) when a cell changes. This heap‑driven paradigm leverages lazy deletion to avoid costly rebuilds: each heap entry stores the sum and its index, and when the top entry becomes stale we discard it until a valid maximum surfaces. The overall approach reduces per‑operation complexity from linear to logarithmic, enabling the algorithm to scale to matrices of size up to 10⁵ × 10⁵ with millions of updates.

Interview Questions on This Problem

Q1How do you efficiently keep track of the maximum row sum after arbitrary cell updates?

Store each row's sum in a max‑heap; when a cell changes, adjust the affected row's sum and push the new value onto the heap. Use lazy deletion to ignore outdated heap entries when extracting the top.

Q2What is lazy deletion in a heap and why is it useful here?

Lazy deletion postpones removal of stale entries; instead of searching the heap to delete an old sum, we simply mark it as invalid and skip it when it reaches the top. This keeps heap operations O(log N) without expensive re‑heapify steps.

Q3Can you compute both max row and max column sums in a single pass?

Yes—while reading the matrix, accumulate row sums in an array and column sums in another, then build two heaps from these arrays in O(N + M) time. No extra passes are required.

Examples

Example 1

Input

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Output

24

Explanation: Row sums: 1+2+3=6, 4+5+6=15, 7+8+9=24. Column sums: 1+4+7=12, 2+5+8=15, 3+6+9=18. Max row sum = 24, max column sum = 18. Result = max(24, 18) = 24.

Example 2

Input

matrix = [[10, 20], [30, 40]]

Output

70

Explanation: Row sums: 10+20=30, 30+40=70. Column sums: 10+30=40, 20+40=60. Max row sum = 70, max column sum = 60. Result = max(70, 60) = 70.

Example 3

Input

matrix = [[5, 5, 5], [5, 5, 5], [5, 5, 5]]

Output

15

Explanation: Row sums: 5+5+5=15 (all rows). Column sums: 5+5+5=15 (all columns). Max row sum = 15, max column sum = 15. Result = max(15, 15) = 15.

Example 4

Input

matrix = [[1, 100], [100, 1]]

Output

101

Explanation: Row sums: 1+100=101, 100+1=101. Column sums: 1+100=101, 100+1=101. Max row sum = 101, max column sum = 101. Result = max(101, 101) = 101.

Constraints

  • 1 <= matrix.length <= 10^3
  • 1 <= matrix[0].length <= 10^3
  • -10^4 <= matrix[i][j] <= 10^4
  • The matrix is guaranteed to be rectangular (all rows have the same length).

Optimal Approach & Strategy

Maintain row and column sum arrays plus two max‑heaps with lazy deletion, updating only the affected sums in O(log N + log M).

Brute Force Approach

Re‑sum all rows and columns after each change, which costs O(N·M) per query.

Verified Code Solutions

JavaScript Solution
Time: O(N·M) initial + O(Q·log(N+M)) for Q updates/queries
/**
 * @param {number[][]} matrix
 * @return {number}
 */
var analyzeMatrix = function(matrix) {
    if (!matrix.length || !matrix[0].length) return 0;
    
    const rows = matrix.length;
    const cols = matrix[0].length;
    
    const rowSums = new Array(rows).fill(0);
    const colSums = new Array(cols).fill(0);
    
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            rowSums[i] += matrix[i][j];
            colSums[j] += matrix[i][j];
        }
    }
    
    const maxRowSum = Math.max(...rowSums);
    const maxColSum = Math.max(...colSums);
    
    return maxRowSum + maxColSum;
};

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.