Workspace Search A 2d Matrix
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Search a 2D Matrix visualizer

Learn Search a 2D Matrix with a step-by-step Binary Search visualizer, JavaScript source code and a worked example. Practice matrices.

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 / 3Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    [
      1,
      3,
      5
    ],
    [
      7,
      9,
      11
    ]
  ],
  "k": 9
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
let n=a[0].length,l=0,r=a.length*n-1;
while(l<=r){
let m=(l+r)>>1,i=Math.floor(m/n),j=m%n,x=a[i][j];
s("Probe flattened midpoint",{
Matrix:a,Cell:[i,j],Bounds:[l,m,r]
});
if(x===k)return true;
if(x<k)l=m+1;
else r=m-1
}
return false
};

Execution canvas

Active Changed
STEP 1

Probe flattened midpoint

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

Matrix2 rows
Cell2 items
Bounds3 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Binary Search · Matrices

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

{
  "a": [
    [
      1,
      3,
      5
    ],
    [
      7,
      9,
      11
    ]
  ],
  "k": 9
}

Execution steps

  1. Probe flattened midpoint

Computed output

true
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  let n=a[0].length,l=0,r=a.length*n-1;
  while(l<=r){
    let m=(l+r)>>1,i=Math.floor(m/n),j=m%n,x=a[i][j];
    s("Probe flattened midpoint",{
      Matrix:a,Cell:[i,j],Bounds:[l,m,r]
    });
    if(x===k)return true;
    if(x<k)l=m+1;
    else r=m-1
  }
  return false
};

Continue learning

Practice related DSA questions in the same topic.