Workspace Set Matrix Zeroes
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Set Matrix Zeroes visualizer

Learn Set Matrix Zeroes with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice optimization and matrix.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 5Execution step
Reference example · JavaScript
Inspect reference input
[
  [
    1,
    1,
    1
  ],
  [
    1,
    0,
    1
  ],
  [
    1,
    1,
    1
  ]
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (m,s)=>{
let r=new Set,c=new Set;
for(let i=0;
i<m.length;
i++)for(let j=0;
j<m[i].length;
j++)if(!m[i][j]){
r.add(i);
c.add(j);
s("Record zero row and column",{
Matrix:m,Rows:[...r],Columns:[...c]
})
}
for(let i=0;
i<m.length;
i++){
for(let j=0;
j<m[i].length;
j++)if(r.has(i)||c.has(j))m[i][j]=0;
s("Apply markers",{
Matrix:m
})
}
return m
};

Execution canvas

Active Changed
STEP 1

Record zero row and column

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Matrix3 rows
Rows1 items
Columns1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Optimization and matrix

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

[
  [
    1,
    1,
    1
  ],
  [
    1,
    0,
    1
  ],
  [
    1,
    1,
    1
  ]
]

Execution steps

  1. Record zero row and column
  2. Apply markers

Computed output

[
  [
    1,
    0,
    1
  ],
  [
    0,
    0,
    0
  ],
  [
    1,
    0,
    1
  ]
]
JavaScript reference implementation
const solve = (m,s)=>{
  let r=new Set,c=new Set;
  for(let i=0;
  i<m.length;
  i++)for(let j=0;
  j<m[i].length;
  j++)if(!m[i][j]){
    r.add(i);
    c.add(j);
    s("Record zero row and column",{
      Matrix:m,Rows:[...r],Columns:[...c]
    })
  }
  for(let i=0;
  i<m.length;
  i++){
    for(let j=0;
    j<m[i].length;
    j++)if(r.has(i)||c.has(j))m[i][j]=0;
    s("Apply markers",{
      Matrix:m
    })
  }
  return m
};

Continue learning

Practice related DSA questions in the same topic.