713972. Fill the Matrix

Medium

Fill the Matrix

Slug: fill-the-matrix--170647

Difficulty: Medium

Id: 713972

Topic Tags: Mathematical, BFS, Algorithms

Company Tags: Oracle

Summary

The "Fill the Matrix" problem involves filling a given matrix with values in such a way that each row and column sum is equal to a given target value. This problem requires a combination of mathematical and algorithmic skills.

Detailed Explanation

To solve this problem, we can use Breadth-First Search (BFS) as our approach. We will start by initializing the first row with values from 1 to n, where n is the number of columns in the matrix. Then, for each subsequent row, we will fill it by iterating over each column and calculating the value based on the sum of the current column and the target value minus the sum of all previous rows.

Here's a step-by-step breakdown:

  1. Initialize the first row with values from 1 to n.
  2. For each subsequent row:
    • Iterate over each column and calculate the value for that cell as follows: matrix[i][j] = target_sum - sum_of_previous_rows - (i * n)
    • where target_sum is the target value, sum_of_previous_rows is the sum of all previous rows, and (i * n) is the sum of all cells in the current row.
  3. Repeat step 2 until the entire matrix is filled.

Here's an example to illustrate this:

View on GeeksforGeeks
public class Main {
    public static void main(String[] args) {
        int[][] matrix = new int[4][5];
        int targetSum = 15;
        for (int i = 0; i < matrix.length; i++) {
            int sumOfPreviousRows = 0;
            for (int j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = targetSum - sumOfPreviousRows - (i * 5);
                sumOfPreviousRows += matrix[i][j];
            }
        }
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.