LeetCode Problem

How to Solve Find Valid Matrix Given Row and Column Sums

The goal is to construct a matrix with non-negative integers, given row and column sums. By applying a greedy strategy and adjusting row and column sums as we populate the matrix, we can efficiently find a valid solution that satisfies the given constraints.

GhostInterview Help

Need help with Find Valid Matrix Given Row and Column Sums without spending extra time grinding it?

GhostInterview can read Find Valid Matrix Given Row and Column Sums from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #1605Greedy choice plus invariant validationReviewed 2026-03-08
Difficulty
Medium
Primary pattern
Greedy choice plus invariant validation
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

The goal is to construct a matrix with non-negative integers, given row and column sums. By applying a greedy strategy and adjusting row and column sums as we populate the matrix, we can efficiently find a valid solution that satisfies the given constraints.

Problem Statement

You are provided two arrays, rowSum and colSum, where rowSum[i] represents the sum of the elements in the ith row of a matrix, and colSum[j] represents the sum of the elements in the jth column of the matrix. Your task is to find a 2D matrix with non-negative integers that satisfies the given row and column sums. It's guaranteed that at least one solution exists.

Return any valid matrix that satisfies the rowSum and colSum conditions. Note that there could be multiple valid matrices that fulfill the requirements, but you only need to find one of them.

Examples

Example 1

Input: rowSum = [3,8], colSum = [4,7]

Output: [[3,0], [1,7]]

0th row: 3 + 0 = 3 == rowSum[0] 1st row: 1 + 7 = 8 == rowSum[1] 0th column: 3 + 1 = 4 == colSum[0] 1st column: 0 + 7 = 7 == colSum[1] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: [[1,2], [3,5]]

Example 2

Input: rowSum = [5,7,10], colSum = [8,6,8]

Output: [[0,5,0], [6,1,0], [2,0,8]]

Example details omitted.

Constraints

  • 1 <= rowSum.length, colSum.length <= 500
  • 0 <= rowSum[i], colSum[i] <= 108
  • sum(rowSum) == sum(colSum)

Solution Approach

Greedy Approach

Iterate through the matrix, selecting the smallest remaining row or column sum. Place the minimum of the current rowSum and colSum in the current cell, then update both rowSum and colSum by subtracting the placed value. Repeat the process until all row and column sums are satisfied.

Matrix Construction

Start with an empty matrix and construct it row by row. Each time, determine the minimal value from the corresponding rowSum and colSum. By iterating through the rows and columns systematically, populate the matrix while ensuring that the sums match the requirements.

Validation

After constructing the matrix, validate it by checking if the sum of each row equals the corresponding value in rowSum and if the sum of each column matches colSum. This ensures the matrix is valid and meets the problem's constraints.

Complexity Analysis

MetricValue
TimeO(N \times M)
SpaceO(1)

The time complexity is O(N x M), where N is the number of rows and M is the number of columns. Space complexity is O(1) since we're modifying the matrix in place and not storing any extra data structures apart from the matrix itself.

What Interviewers Usually Probe

  • Check if the candidate follows the greedy strategy and constructs the matrix step by step.
  • Look for any validation steps after matrix construction to ensure the row and column sums are satisfied.
  • Assess how efficiently the candidate updates the row and column sums during the matrix population process.

Common Pitfalls or Variants

Common pitfalls

  • Failing to update the rowSum and colSum properly after each placement.
  • Not validating the final matrix to ensure the row and column sums match the expected values.
  • Incorrectly handling edge cases such as when row or column sums are zero.

Follow-up variants

  • Given a larger matrix, ensure the algorithm scales well with larger inputs by optimizing the matrix traversal.
  • Add constraints where some elements of the matrix must be zero, and handle such situations while maintaining the row and column sum requirements.
  • Consider adding further constraints, such as ensuring the matrix contains only certain numbers or patterns, and adapt the greedy approach accordingly.

How GhostInterview Helps

  • GhostInterview's step-by-step guidance helps simulate the greedy approach, ensuring the candidate understands the process of adjusting row and column sums.
  • The platform provides immediate feedback to highlight areas where the candidate might be making mistakes in the greedy approach, ensuring they grasp the necessary steps.
  • GhostInterview assists in validating the matrix construction by checking if the row and column sums meet the required values, encouraging best practices.

Topic Pages

FAQ

What is the primary strategy used to solve 'Find Valid Matrix Given Row and Column Sums'?

The primary strategy is to use a greedy approach, iterating through the matrix and placing the smallest of the remaining rowSum or colSum values in each cell, updating the sums after each placement.

How do I ensure that the matrix I construct satisfies the row and column sums?

After constructing the matrix, verify that the sum of each row and column matches the corresponding values in rowSum and colSum. This acts as a final validation step.

Can there be multiple valid matrices for the problem?

Yes, there can be multiple valid matrices, as long as they satisfy the row and column sum conditions. The problem only requires finding one valid solution.

What are some common pitfalls in solving this problem?

Common mistakes include failing to update the rowSum and colSum after each matrix entry, skipping the validation step, or not handling edge cases such as zero sums correctly.

How can I optimize the solution for larger matrices?

The algorithm scales well for larger matrices, but you may optimize by using more efficient ways to select the smallest row or column sum and ensure that the matrix construction is done in minimal time.

GhostInterview Solver

Need direct help with Find Valid Matrix Given Row and Column Sums instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Find Valid Matrix Given Row and Column Sums from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.