The iron ML notebook
  • The iron data science notebook
  • ML & Data Science
    • Frequent Questions
      • Discriminative vs Generative models
      • Supervised vs Unsupervised learning
      • Batch vs Online Learning
      • Instance-based vs Model-based Learning
      • Bias-Variance Tradeoff
      • Probability vs Likelihood
      • Covariance vs Correlation Matrix
      • Precision vs Recall
      • How does a ROC curve work?
      • Ridge vs Lasso
      • Anomaly detection methods
      • How to deal with imbalanced datasets?
      • What is "Statistically Significant"?
      • Recommendation systems methods
    • Statistics
      • The basics
      • Distributions
      • Sampling
      • IQR
      • Z-score
      • F-statistic
      • Outliers
      • The bayesian basis
      • Statistic vs Parameter
      • Markov Monte Carlo Chain
    • ML Techniques
      • Pre-process
        • PCA
      • Loss functions
      • Regularization
      • Optimization
      • Metrics
        • Distance measures
      • Activation Functions
      • Selection functions
      • Feature Normalization
      • Cross-validation
      • Hyperparameter tuning
      • Ensemble methods
      • Hard negative mining
      • ML Serving
        • Quantization
        • Kernel Auto-Tuning
        • NVIDIA TensorRT vs ONNX Runtime
    • Machine Learning Algorithms
      • Supervised Learning
        • Support Vector Machines
        • Adaptative boosting
        • Gradient boosting
        • Regression algorithms
          • Linear Regression
          • Lasso regression
          • Multi Layer Perceptron
        • Classification algorithms
          • Perceptron
          • Logistic Regression
          • Multilayer Perceptron
          • kNN
          • Naive Bayes
          • Decision Trees
          • Random Forest
          • Gradient Boosted Trees
      • Unsupervised learning
        • Clustering
          • Clustering metrics
          • kMeans
          • Gaussian Mixture Model
          • Hierarchical clustering
          • DBSCAN
      • Cameras
        • Intrinsic and extrinsic parameters
    • Computer Vision
      • Object Detection
        • Two-Stage detectors
          • Traditional Detection Models
          • R-CNN
          • Fast R-CNN
          • Faster R-CNN
        • One-Stage detectors
          • YOLO
          • YOLO v2
          • YOLO v3
          • YOLOX
        • Techniques
          • NMS
          • ROI Pooling
        • Metrics
          • Objectness Score
          • Coco Metrics
          • IoU
      • MOT
        • SORT
        • Deep SORT
  • Related Topics
    • Intro
    • Python
      • Global Interpreter Lock (GIL)
      • Mutability
      • AsyncIO
    • SQL
    • Combinatorics
    • Data Engineering Questions
    • Distributed computation
      • About threads & processes
      • REST vs gRPC
  • Algorithms & data structures
    • Array
      • Online Stock Span
      • Two Sum
      • Best time to by and sell stock
      • Rank word combination
      • Largest subarray with zero sum
    • Binary
      • Sum of Two Integers
    • Tree
      • Maximum Depth of Binary Tree
      • Same Tree
      • Invert/Flip Binary Tree
      • Binary Tree Paths
      • Binary Tree Maximum Path Sum
    • Matrix
      • Set Matrix Zeroes
    • Linked List
      • Reverse Linked List
      • Detect Cycle
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
    • String
      • Longest Substring Without Repeating Characters
      • Longest Repeating Character Replacement
      • Minimum Window Substring
    • Interval
    • Graph
    • Heap
    • Dynamic Programming
      • Fibonacci
      • Grid Traveler
      • Can Sum
      • How Sum
      • Best Sum
      • Can Construct
      • Count Construct
      • All Construct
      • Climbing Stairs
Powered by GitBook
On this page

Was this helpful?

  1. Algorithms & data structures
  2. Matrix

Set Matrix Zeroes

PreviousMatrixNextLinked List

Last updated 1 year ago

Was this helpful?

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        self.setZerosOpti(matrix)
        
    def setZerosAdditionalMemory(self, matrix: List[List[int]]) -> None:
        """
        Time Complexity: O(M×N) where M and N are the number of rows 
        and columns respectively

        Space Complexity: O(M+N)
            One array to store zeros in the horizontal axis and another one
            to store the ones from the vertical array.
        """        
        
        horizontal_zeros = []
        vertical_zeros = []
        
        for i, row in enumerate(matrix):
            for j, value in enumerate(row):
                if value == 0:                    
                    horizontal_zeros.append(i)
                    vertical_zeros.append(j)

        
        for i, row in enumerate(matrix):
            for j, value in enumerate(row):
                if i in horizontal_zeros or j in vertical_zeros:
                    matrix[i][j] = 0

        
    def setZerosAdditionalTime(self, matrix: List[List[int]]) -> None:
        """
        Time Complexity: O(M²×N²)
        
        Space Complexity: O(1)
        """
        
        for i, row in enumerate(matrix):
            for j, value in enumerate(row):
                if value == 0:                    
                    print(f"{i}, {j}")
                    # set zeros in row
                    for k, item in enumerate(row):
                        matrix[i][k] = "*" if matrix[i][k] != 0 else 0
                    
                    # set zeros in column
                    for r in matrix:
                        r[j] = "*" if r[j] != 0 else 0
                        
        for i, row in enumerate(matrix):
            for j, value in enumerate(row):
                if value == "*":
                    matrix[i][j] = 0
                    
    def setZerosOpti(self, matrix: List[List[int]]) -> None:    
        """
        Time Complexity: O(M×N)
        
        Space Complexity: O(1)
        """
        
        first_col = False
        num_rows = len(matrix)
        num_cols = len(matrix[0])
        for i in range(num_rows):
            # Since first cell for both first row and first column is the same 
            # i.e. matrix[0][0]
            # We can use an additional variable for either the first row/column.
            # For this solution we are using an additional variable for the first             
            # column and using matrix[0][0] for the first row.
            if matrix[i][0] == 0:
                first_col = True
            for j in range(1, num_cols):
                # If an element is zero, we set the first element of the 
                # corresponding row and column to 0
                if matrix[i][j]  == 0:
                    matrix[0][j] = 0
                    matrix[i][0] = 0
        
        # Iterate over the array once again and using the first row 
        # and first column, update the elements.
        for i in range(num_rows-1 , -1, -1):
            for j in range(num_cols-1, 0, -1):
                if not matrix[i][0] or not matrix[0][j]:
                    matrix[i][j] = 0
            if first_col:
                matrix[i][0] = 0
https://leetcode.com/problems/set-matrix-zeroes/