Logo

dev-resources.site

for different kinds of informations.

LeetCode Challenge: 73. Set Matrix Zeroes - JavaScript Solution πŸš€

Published at
1/11/2025
Categories
javascript
programming
leetcode
interview
Author
rahulgithubweb
Author
14 person written this
rahulgithubweb
open
LeetCode Challenge: 73. Set Matrix Zeroes - JavaScript Solution πŸš€

Top Interview 150

The Set Matrix Zeroes problem is a common challenge involving in-place matrix manipulation. Let’s solve LeetCode 73: Set Matrix Zeroes step by step, focusing on achieving the O(1) space complexity requirement.


πŸš€ Problem Description

Given an mΓ—n matrix:

  • If an element is 0, set its entire row and column to 0.
  • Perform this operation in-place.

πŸ’‘ Examples

Example 1

Mat1

Input: matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]  
Output: [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Enter fullscreen mode Exit fullscreen mode

Example 2

Mat2

Input: matrix = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]  
Output: [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
Enter fullscreen mode Exit fullscreen mode

Constraints

  • 1 ≀ m,n ≀ 200
  • -2^31 ≀ matrix[i][j]≀ 2^31-1

πŸ† JavaScript Solution

We can solve this problem efficiently using the first row and first column of the matrix as markers to indicate which rows and columns need to be set to 0.


Implementation

var setZeroes = function(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    let firstRowHasZero = false;
    let firstColHasZero = false;

    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (matrix[i][j] === 0) {
                if (i === 0) firstRowHasZero = true;
                if (j === 0) firstColHasZero = true;
                matrix[i][0] = 0; // Mark the first column
                matrix[0][j] = 0; // Mark the first row
            }
        }
    }

    for (let i = 1; i < rows; i++) {
        for (let j = 1; j < cols; j++) {
            if (matrix[i][0] === 0 || matrix[0][j] === 0) {
                matrix[i][j] = 0;
            }
        }
    }

    if (firstRowHasZero) {
        for (let j = 0; j < cols; j++) {
            matrix[0][j] = 0;
        }
    }

    if (firstColHasZero) {
        for (let i = 0; i < rows; i++) {
            matrix[i][0] = 0;
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

πŸ” How It Works

  1. Mark the First Row and Column:

    • Traverse the matrix to find zero elements.
    • Use the first row and first column as markers to remember which rows and columns need to be zeroed.
  2. Set Elements to Zero:

    • For every cell not in the first row or column, check the corresponding marker.
    • If the marker indicates zero, set the cell to zero.
  3. Handle the First Row and Column:

    • If the first row or first column originally contained zeros, set all their elements to zero.

πŸ”‘ Complexity Analysis

  • Time Complexity: O(mβ‹…n), where m is the number of rows and n is the number of columns.

    • Each cell is visited once during marking and once during the update.
  • Space Complexity: O(1), since no additional data structures are used.


πŸ“‹ Dry Run

Input: matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]

  • Step 1: Mark the First Row and Column

Step1

  • Step2: Update the Matrix

Step2

  • Step 3: Update the First Row and Column

Step3

Output:

[[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Enter fullscreen mode Exit fullscreen mode

✨ Pro Tips for Interviews

  1. Explain Constant Space:

    • Highlight how you use the matrix itself for marking instead of additional space.
  2. Clarify Edge Cases:

    • Single row/column matrices.
    • Matrices where all elements are zero.
  3. Discuss Optimization:

    • Compare the O(mn) space solution to the O(1) optimized approach.

πŸ“š Learn More

Check out the full explanation and code walkthrough on my previous Dev.to post:
πŸ‘‰ Rotate Image - JavaScript Solution

What’s your preferred method to solve this problem? Let’s discuss! πŸš€


Study

leetcode Article's
30 articles in total
Favicon
Neetcode Roadmap Part 1
Favicon
2429. Minimize XOR
Favicon
A tΓ©cnica dos dois ponteiros
Favicon
2657. Find the Prefix Common Array of Two Arrays
Favicon
Time Complexity, Big-O for Beginners
Favicon
LeetCode Challenge: 383. Ransom Note - JavaScript Solution πŸš€
Favicon
3223. Minimum Length of String After Operations
Favicon
Leet code
Favicon
2116. Check if a Parentheses String Can Be Valid
Favicon
LeetCode Challenge: 73. Set Matrix Zeroes - JavaScript Solution πŸš€
Favicon
LeetCode Challenge: 290. Word Pattern - JavaScript Solution πŸš€
Favicon
LeetCode Challenge: 205. Isomorphic Strings - JavaScript Solution πŸš€
Favicon
Leetcode: 73 Set Matrix Zeroes
Favicon
LeetCode Challenge: 36.Valid Sudoku - JavaScript Solution πŸš€
Favicon
Count prefix and suffix I and II
Favicon
Leetcode Blind 75
Favicon
Rabin Karp (hashing) String pattern matching
Favicon
Leetcode β€” 2942. Find Words Containing Character
Favicon
Automating Your LeetCode Journey: Building an Enterprise-Grade LeetCode to GitHub Sync System
Favicon
Understanding the XOR Operator: A Powerful Tool in Computing
Favicon
Kadane's Algorithm: Leetcode 53 Maximum subarray
Favicon
1768. Merge Strings Alternately
Favicon
Find all anagrams in the string[Fixed Window pattern]
Favicon
No of ways to split Array
Favicon
Leetcode β€” 3289. The Two Sneaky Numbers of Digitville
Favicon
Range sum query 2D - Immutable
Favicon
Range Sum Query - Immutable
Favicon
Count vowel strings in ranges
Favicon
Yay! Reached 1035+ days Daily Coding Streak on Leetcode!
Favicon
Leetcode 75. Sort Colors

Featured ones: