Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Set Matrix Zeroes
Optimal Solution



Problem Statement

Given a 2D matrix, your task is to modify it in-place such that if any cell in the matrix is 0, you set its entire row and column to 0.

This transformation must be done in-place, meaning you should not use extra space for a duplicate matrix. The challenge is to achieve this optimally, using constant space.

If the matrix is empty, it should remain unchanged.

Examples

Input MatrixOutput MatrixDescription
[[1, 2, 3],
[4, 0, 6],
[7, 8, 9]]
[[1, 0, 3],
[0, 0, 0],
[7, 0, 9]]
Zero at (1,1) sets row 1 and column 1 to 0
[[0, 1],
[1, 1]]
[[0, 0],
[0, 1]]
Zero at (0,0) sets row 0 and column 0 to 0
[[1, 1],
[1, 1]]
[[1, 1],
[1, 1]]
No zero in the matrix; no changes made
[[0, 0],
[0, 0]]
[[0, 0],
[0, 0]]
All values already zero; output is unchanged
[][]Empty matrix; no operation needed

Solution

To solve this problem efficiently, we need to identify every cell that contains a 0 and then set the entire row and column of that cell to 0. However, doing this naively with extra space (like a separate matrix or two hash sets) increases the space complexity.

The optimal way to solve it in-place is to use the matrix itself as storage. More specifically, we use the first row and first column of the matrix as markers.

Step-by-step Understanding

1. First, we scan the matrix to check whether the first row or first column contain any zeros. We use two boolean flags to remember this because we’ll later overwrite these rows/columns with markers.

2. Next, we traverse the entire matrix (excluding first row and column). If we find a cell with value 0 at mat[i][j], we mark its row and column by setting mat[i][0] = 0 and mat[0][j] = 0.

3. Then we scan the matrix again (excluding the first row and column). If either mat[i][0] or mat[0][j] is 0, it means the cell should be zeroed out, so we set mat[i][j] = 0.

4. Lastly, we update the first row and first column based on our flags. If the first row originally had a 0, we set the entire row to 0. Same for the first column.

Handling Special Cases

  • No zero exists: In this case, the matrix remains unchanged after the scan.
  • All elements are zero: The matrix remains fully zero as expected.
  • Zeros only in first row/column: This is why we track the first row/column with separate flags—so we don't lose this information while using them as markers.
  • Empty matrix: If the matrix is empty (i.e., has no rows), we simply do nothing and return it as is.

This technique is efficient because it avoids the need for extra memory and ensures the matrix is modified directly. It operates in O(n × m) time and O(1) space complexity (excluding input/output).

Visualization

Algorithm Steps

  1. Given a 2D matrix mat.
  2. Use the first row and first column as markers to indicate if a row or column should be set to zero.
  3. Check if the first row and first column themselves contain any zero using two separate flags.
  4. Traverse the rest of the matrix:
  5. → If any element is 0, mark its row and column in the first row and column.
  6. Traverse the matrix again (excluding first row and column):
  7. → If mat[i][0] == 0 or mat[0][j] == 0, set mat[i][j] = 0.
  8. Finally, update the first row and first column based on the flags.

Code

Python
JavaScript
Java
C++
C
def set_zeroes(matrix):
    rows, cols = len(matrix), len(matrix[0])
    first_row_zero = any(matrix[0][j] == 0 for j in range(cols))
    first_col_zero = any(matrix[i][0] == 0 for i in range(rows))

    for i in range(1, rows):
        for j in range(1, cols):
            if matrix[i][j] == 0:
                matrix[i][0] = 0
                matrix[0][j] = 0

    for i in range(1, rows):
        for j in range(1, cols):
            if matrix[i][0] == 0 or matrix[0][j] == 0:
                matrix[i][j] = 0

    if first_row_zero:
        for j in range(cols):
            matrix[0][j] = 0

    if first_col_zero:
        for i in range(rows):
            matrix[i][0] = 0

    return matrix

# Sample Input
mat = [[1,1,1],[1,0,1],[1,1,1]]
print("Updated Matrix:", set_zeroes(mat))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M