Bird
Raised Fist0
DSA Javaprogramming~15 mins

Set Matrix Zeroes In Place in DSA Java - Deep Dive

Choose your learning style10 modes available
Overview - Set Matrix Zeroes In Place
What is it?
Set Matrix Zeroes In Place is a problem where you modify a given 2D matrix so that if any element is zero, its entire row and column become zero. The challenge is to do this without using extra space for another matrix. You change the matrix directly, saving memory and making the solution efficient.
Why it matters
This problem teaches how to cleverly use existing data structures to save space, which is important in real-world applications where memory is limited. Without this approach, programs might waste memory or run slower by copying data unnecessarily. Understanding this helps write efficient code that works well even with large data.
Where it fits
Before this, you should know how to work with 2D arrays and basic loops. After this, you can learn about space optimization techniques and other matrix manipulation problems like rotating or searching matrices.
Mental Model
Core Idea
Use the first row and first column of the matrix as markers to remember which rows and columns should be zeroed, avoiding extra space.
Think of it like...
Imagine a classroom seating chart where if a student is sick (zero), you mark the entire row and column on the chart to keep those seats empty. Instead of making a new chart, you use the first row and column as your notes to remember which seats to clear.
Matrix before:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 1  2  0  4 β”‚
β”‚ 5  6  7  8 β”‚
β”‚ 9  0 11 12 β”‚
β”‚13 14 15 16 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Markers set in first row and column:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 1  0  0  4 β”‚
β”‚ 5  6  7  8 β”‚
β”‚ 0  0 11 12 β”‚
β”‚13 14 15 16 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Final matrix after zeroing:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 0  0  0  0 β”‚
β”‚ 5  0  0  8 β”‚
β”‚ 0  0  0  0 β”‚
β”‚13  0  0 16 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Build-Up - 6 Steps
1
FoundationUnderstanding the Problem Statement
πŸ€”
Concept: Learn what it means to set matrix zeroes in place and why direct modification is required.
You have a 2D matrix of numbers. Whenever you find a zero in the matrix, you must change all numbers in that zero's row and column to zero. The catch is you must do this without creating a new matrix to store changes. You must update the original matrix directly.
Result
You know the problem goal: zero out rows and columns based on zeros found, modifying the matrix itself.
Understanding the problem clearly is the first step to solving it efficiently without extra memory.
2
FoundationNaive Approach with Extra Space
πŸ€”
Concept: Use extra arrays to track which rows and columns need zeroing.
Create two arrays: one for rows and one for columns. Scan the matrix once. When you find a zero, mark its row and column in these arrays. Then, in a second pass, set matrix elements to zero if their row or column is marked. This uses extra space proportional to the matrix size.
Result
Matrix is correctly zeroed, but extra memory is used for tracking.
This approach works but wastes memory, which is a problem for large matrices or limited environments.
3
IntermediateUsing Matrix Itself as Marker
πŸ€”
Concept: Reuse the first row and first column of the matrix to store zero markers.
Instead of extra arrays, use the first row to mark columns that need zeroing and the first column to mark rows. First, check if the first row and first column themselves have zeros (store this info separately). Then scan the rest of the matrix, marking zeros in the first row and column. Finally, zero rows and columns based on these markers.
Result
Matrix is zeroed correctly without extra arrays, saving space.
Reusing the matrix for markers cleverly reduces space from O(m+n) to O(1).
4
IntermediateHandling First Row and Column Separately
πŸ€”Before reading on: do you think the first row and first column can be marked the same way as others without extra care? Commit to yes or no.
Concept: Because the first row and column are used as markers, we must separately track if they originally had zeros to avoid losing that info.
Check if the first row has any zero and store in a boolean. Do the same for the first column. After zeroing other rows and columns using markers, zero the first row and/or column if needed based on these booleans.
Result
The first row and column are correctly zeroed if they originally contained zeros.
Separately tracking the first row and column prevents overwriting marker info and ensures correctness.
5
AdvancedIn-Place Java Implementation
πŸ€”Before reading the code: do you think the solution can be done with just a few variables and no extra arrays? Commit to yes or no.
Concept: Implement the in-place zeroing algorithm in Java using the first row and column as markers and two booleans for their original zero states.
public class Solution { public void setZeroes(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; boolean firstRowZero = false; boolean firstColZero = false; // Check first row for zero for (int c = 0; c < cols; c++) { if (matrix[0][c] == 0) { firstRowZero = true; break; } } // Check first column for zero for (int r = 0; r < rows; r++) { if (matrix[r][0] == 0) { firstColZero = true; break; } } // Use first row and column as markers for (int r = 1; r < rows; r++) { for (int c = 1; c < cols; c++) { if (matrix[r][c] == 0) { matrix[r][0] = 0; matrix[0][c] = 0; } } } // Zero rows based on markers for (int r = 1; r < rows; r++) { if (matrix[r][0] == 0) { for (int c = 1; c < cols; c++) { matrix[r][c] = 0; } } } // Zero columns based on markers for (int c = 1; c < cols; c++) { if (matrix[0][c] == 0) { for (int r = 1; r < rows; r++) { matrix[r][c] = 0; } } } // Zero first row if needed if (firstRowZero) { for (int c = 0; c < cols; c++) { matrix[0][c] = 0; } } // Zero first column if needed if (firstColZero) { for (int r = 0; r < rows; r++) { matrix[r][0] = 0; } } } }
Result
The matrix is modified in place with all appropriate rows and columns zeroed.
This code shows how to implement the space-saving technique practically and correctly.
6
ExpertEdge Cases and Performance Considerations
πŸ€”Before reading on: do you think this algorithm handles single row or single column matrices correctly? Commit to yes or no.
Concept: Consider special cases like matrices with one row or one column, or all zeros, and analyze time and space complexity.
The algorithm works for any matrix size, including 1x1 or 1xN. It runs in O(m*n) time because it scans the matrix a few times but only uses O(1) extra space. Watch out for matrices where the first row or column is all zeros, as the separate booleans handle these correctly. Also, the method avoids unnecessary writes by only zeroing marked rows and columns.
Result
The solution is robust and efficient for all valid inputs.
Understanding edge cases and complexity ensures the solution is production-ready and reliable.
Under the Hood
The algorithm uses the first row and first column of the matrix as storage to mark which rows and columns should be zeroed. This avoids extra memory allocation. It first scans the matrix to set these markers, then uses them to zero out the matrix in a second pass. Special booleans track if the first row or column originally contained zeros to avoid losing that information during marking.
Why designed this way?
This design was chosen to optimize space usage. Using extra arrays for markers costs O(m+n) space, which can be large for big matrices. By reusing the matrix itself, the algorithm achieves O(1) extra space. The tradeoff is careful handling of the first row and column to avoid overwriting important data.
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Scan matrix to find zeros      β”‚
β”‚ and mark first row/column      β”‚
β”‚ as indicators (markers)        β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Use booleans to remember if    β”‚
β”‚ first row/column had zeros     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Zero rows and columns based on β”‚
β”‚ markers in first row/column    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Zero first row and column if   β”‚
β”‚ booleans indicate original zerosβ”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Myth Busters - 4 Common Misconceptions
Quick: Do you think you can zero rows and columns immediately when you find a zero in the matrix? Commit to yes or no.
Common Belief:You can set zeros in rows and columns right away when you find a zero element during the first scan.
Tap to reveal reality
Reality:If you zero rows and columns immediately, you may overwrite zeros that haven't been found yet, causing incorrect results.
Why it matters:Immediate zeroing corrupts the matrix before all zeros are found, leading to wrong rows and columns being zeroed.
Quick: Do you think the first row and first column can be treated like any other row or column for marking? Commit to yes or no.
Common Belief:The first row and first column can be used as markers without special handling.
Tap to reveal reality
Reality:The first row and column need separate tracking because they serve as markers and may originally contain zeros themselves.
Why it matters:Ignoring this causes loss of information about whether the first row or column should be zeroed, leading to incorrect final matrix.
Quick: Do you think extra space is always necessary to solve this problem? Commit to yes or no.
Common Belief:You must use extra arrays or matrices to track zero rows and columns.
Tap to reveal reality
Reality:You can solve the problem in place using the matrix itself as storage, requiring only constant extra space.
Why it matters:Believing extra space is necessary prevents learning the optimal in-place solution, which is important for memory efficiency.
Quick: Do you think this algorithm runs in less than O(m*n) time? Commit to yes or no.
Common Belief:The problem can be solved faster than scanning the entire matrix multiple times.
Tap to reveal reality
Reality:The algorithm must scan the matrix at least once fully, so O(m*n) time is the best possible for this problem.
Why it matters:Expecting faster than O(m*n) leads to wasted effort on impossible optimizations.
Expert Zone
1
The order of zeroing rows and columns matters; zeroing columns before rows or vice versa can cause subtle bugs if not handled carefully.
2
Using the first row and column as markers means the original data in those positions is temporarily overwritten, so separate flags are essential to preserve their original zero state.
3
In some languages or environments, minimizing writes to the matrix can improve performance, so skipping zeroing cells already zero can be a useful optimization.
When NOT to use
This in-place approach is not suitable if the matrix is immutable or if you must preserve the original matrix unchanged. In such cases, use extra space to create a copy. Also, if the matrix is sparse and very large, specialized sparse matrix techniques might be more efficient.
Production Patterns
In production, this pattern is used in image processing to mask rows and columns, in database systems to mark invalid rows/columns, and in spreadsheet software to quickly update large tables without extra memory. It also appears in coding interviews as a classic space optimization problem.
Connections
In-place Algorithms
Builds-on
Understanding how to reuse existing data structures for marking is a core idea in many in-place algorithms, reducing memory usage.
Bitmasking
Similar pattern
Using parts of the data structure itself as markers is conceptually similar to bitmasking, where bits within a number represent flags.
Spreadsheet Conditional Formatting
Real-world application
The logic of marking rows and columns based on conditions mirrors how spreadsheet software highlights or formats cells based on values.
Common Pitfalls
#1Zeroing rows and columns immediately when a zero is found.
Wrong approach:for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (matrix[r][c] == 0) { for (int k = 0; k < cols; k++) matrix[r][k] = 0; for (int k = 0; k < rows; k++) matrix[k][c] = 0; } } }
Correct approach:Use markers first, then zero after scanning: // First pass: mark rows and columns // Second pass: zero rows and columns based on markers
Root cause:Immediate zeroing changes the matrix during scanning, hiding other zeros and causing incorrect zeroing.
#2Not tracking if the first row or column originally had zeros.
Wrong approach:// Use first row and column as markers but skip checking their original zero state // Then zero based on markers without separate flags
Correct approach:boolean firstRowZero = false; boolean firstColZero = false; // Check first row and column before marking // Use these flags to zero first row and column at the end
Root cause:Overwriting first row/column markers without remembering their original zero state loses critical information.
#3Using extra arrays unnecessarily when in-place is possible.
Wrong approach:boolean[] rows = new boolean[matrix.length]; boolean[] cols = new boolean[matrix[0].length]; // Use these arrays to mark zeros
Correct approach:Use first row and column of matrix as markers to save space.
Root cause:Not realizing the matrix itself can store marker info leads to inefficient solutions.
Key Takeaways
Set Matrix Zeroes In Place requires modifying the matrix directly without extra space by cleverly using the first row and column as markers.
Separately tracking whether the first row and first column originally contain zeros is essential to avoid losing information during marking.
Immediate zeroing upon finding zeros corrupts the matrix and leads to incorrect results; marking first then zeroing is the correct approach.
This problem is a classic example of space optimization in algorithms, teaching how to reuse existing data structures effectively.
Understanding edge cases and the algorithm's time and space complexity ensures robust and efficient solutions.

Practice

(1/5)
1. What is the main goal of the Set Matrix Zeroes In Place problem?
easy
A. Count the number of zero elements in the matrix.
B. Modify the matrix so that if an element is 0, its entire row and column become 0 without using extra space.
C. Sort each row of the matrix in ascending order.
D. Find the sum of all elements in the matrix.

Solution

  1. Step 1: Understand the problem requirement

    The problem asks to set entire rows and columns to zero if any element in them is zero, modifying the matrix directly.
  2. Step 2: Recognize the constraint of in-place modification

    We must do this without using extra space for another matrix or large data structures.
  3. Final Answer:

    Modify the matrix so that if an element is 0, its entire row and column become 0 without using extra space. -> Option B
  4. Quick Check:

    Goal = Set rows and columns to zero in-place [OK]
Hint: Remember: zero means zero entire row and column in-place [OK]
Common Mistakes:
  • Using extra space like another matrix
  • Only zeroing rows or columns, not both
  • Not modifying the matrix in-place
2. Which of the following Java code snippets correctly declares a 2D integer matrix named matrix with 3 rows and 4 columns?
easy
A. int[][] matrix = new int[3][4];
B. int matrix[][] = new int[4][3];
C. int matrix[3][4];
D. int matrix = new int[3][4];

Solution

  1. Step 1: Recall Java 2D array declaration syntax

    In Java, 2D arrays are declared as int[][] name = new int[rows][columns];.
  2. Step 2: Match the correct dimensions

    int[][] matrix = new int[3][4]; uses 3 rows and 4 columns correctly. int matrix[][] = new int[4][3]; reverses dimensions, C is invalid syntax, D misses array brackets.
  3. Final Answer:

    int[][] matrix = new int[3][4]; -> Option A
  4. Quick Check:

    Java 2D array syntax = int[][] matrix = new int[3][4]; [OK]
Hint: Use int[][] for 2D arrays with new int[rows][cols] [OK]
Common Mistakes:
  • Swapping rows and columns in new int[][]
  • Using C-style array declaration
  • Missing brackets in declaration
3. What will be the state of the matrix after running the following Java code snippet for setting matrix zeroes in place?
int[][] matrix = {
  {1, 2, 0},
  {4, 5, 6},
  {7, 0, 9}
};

// After applying setZeroes(matrix) method
// (method sets entire row and column to zero if element is zero)
medium
A. [[0, 0, 0], [4, 0, 0], [0, 0, 0]]
B. [[1, 0, 0], [4, 0, 0], [0, 0, 0]]
C. [[0, 0, 0], [4, 5, 0], [0, 0, 0]]
D. [[0, 2, 0], [4, 0, 6], [0, 0, 0]]

Solution

  1. Step 1: Identify zero elements and their rows and columns

    Zeros are at positions (0,2) and (2,1). Rows 0 and 2, columns 1 and 2 must be zeroed.
  2. Step 2: Set entire rows and columns to zero

    Row 0 becomes [0,0,0], row 2 becomes [0,0,0]. Column 1 and 2 in row 1 become 0, so row 1 becomes [4,0,0].
  3. Final Answer:

    [[0, 0, 0], [4, 0, 0], [0, 0, 0]] -> Option A
  4. Quick Check:

    Zero rows and columns set correctly = [[0, 0, 0], [4, 0, 0], [0, 0, 0]] [OK]
Hint: Mark zero rows and columns first, then update matrix [OK]
Common Mistakes:
  • Only zeroing rows or columns, not both
  • Not updating all affected cells
  • Overwriting zeros too early
4. Consider this buggy Java code snippet for setting matrix zeroes in place:
public void setZeroes(int[][] matrix) {
  int rows = matrix.length;
  int cols = matrix[0].length;
  boolean[] rowZero = new boolean[rows];
  boolean[] colZero = new boolean[cols];

  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      if (matrix[i][j] == 0) {
        rowZero[i] = true;
        colZero[j] = true;
      }
    }
  }

  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      if (rowZero[i] || colZero[j]) {
        matrix[i][j] = 0;
      }
    }
  }
}
What is the main issue with this code regarding the problem constraints?
medium
A. It modifies the matrix before checking all zeros, causing incorrect results.
B. It does not correctly identify zero elements in the matrix.
C. It causes an ArrayIndexOutOfBoundsException.
D. It uses extra space proportional to rows and columns, violating in-place requirement.

Solution

  1. Step 1: Analyze space usage of the code

    The code uses two boolean arrays, rowZero and colZero, sized by rows and columns, which is extra space.
  2. Step 2: Compare with problem constraints

    The problem requires in-place modification without extra space, so using these arrays violates the constraint.
  3. Final Answer:

    It uses extra space proportional to rows and columns, violating in-place requirement. -> Option D
  4. Quick Check:

    Extra space used = violates in-place [OK]
Hint: Avoid extra arrays; use matrix first row/column as markers [OK]
Common Mistakes:
  • Ignoring space constraints
  • Using extra arrays for marking
  • Not handling first row/column carefully
5. You have a 4x4 matrix:
1 2 3 4
5 0 7 8
9 10 11 12
0 14 15 16
Using the in-place method for setting matrix zeroes, what will be the matrix after the operation?
hard
A. [[0, 0, 3, 4], [0, 0, 0, 0], [0, 0, 11, 12], [0, 0, 15, 16]]
B. [[0, 0, 0, 4], [0, 0, 0, 0], [0, 0, 0, 12], [0, 0, 0, 0]]
C. [[0, 0, 3, 4], [0, 0, 0, 0], [0, 0, 11, 12], [0, 0, 0, 0]]
D. [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Solution

  1. Step 1: Identify zero positions and mark rows and columns

    Zeros at (1,1) and (3,0). Rows 1 and 3, columns 0 and 1 must be zeroed.
  2. Step 2: Set zeros for affected rows and columns

    Rows 1 and 3 become entirely zeros. Columns 0 and 1 become zeros across all rows, resulting in row 0: [0,0,3,4]; row 2: [0,0,11,12].
  3. Final Answer:

    [[0, 0, 3, 4], [0, 0, 0, 0], [0, 0, 11, 12], [0, 0, 0, 0]] -> Option C
  4. Quick Check:

    Zero rows and columns updated correctly = [[0, 0, 3, 4], [0, 0, 0, 0], [0, 0, 11, 12], [0, 0, 0, 0]] [OK]
Hint: Mark first row/column, then update matrix carefully [OK]
Common Mistakes:
  • Zeroing entire rows or columns unnecessarily
  • Missing zeros in some cells
  • Not handling first row and column markers properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard