MEDIUM NC#138 Blind #46 Math & Geometry

73. Set Matrix Zeroes

๐Ÿ“– Problem

Given an m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place with O(1) extra space.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Use first row and first column as markers
  • โ†’ Track if first row/col needs to be zeroed separately
  • โ†’ First pass: use first row/col to mark which rows/cols need zeroing
  • โ†’ Second pass: set cells to 0 based on markers
  • โ†’ Finally zero first row/col if needed
  • โ†’ Time: O(m * n), Space: O(1)

๐Ÿงญ Prerequisites

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse first row and first column as markers
  • โ€ขTrack if first row/col needs to be zeroed separately
  • โ€ขFirst pass: use first row/col to mark which rows/cols need zeroing

Common Pitfalls

  • โ€ขSecond pass: set cells to 0 based on markers
  • โ€ขFinally zero first row/col if needed
  • โ€ขTime: O(m * n), Space: O(1)

๐Ÿงช Test Cases

Test Case 1
Not run
Input:
setZeroes(matrix1);
Expected:
null
Test Case 2
Not run
Input:
setZeroes(matrix2);
Expected:
null
Test Case 3
Not run
Input:
setZeroes(matrix: number[][]);
Expected:
Computed from hidden reference

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit