Workspace Median In Row Wise Sorted Matrix
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Median in Row Wise Sorted Matrix visualizer

Learn Median in Row Wise Sorted 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 / 4Execution step
Reference example · JavaScript
Inspect reference input
[
  [
    1,
    3,
    5
  ],
  [
    2,
    6,
    9
  ],
  [
    3,
    6,
    9
  ]
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let l=Math.min(...a.map(r=>r[0])),r=Math.max(...a.map(r=>r.at(-1))),k=Math.floor(a.length*a[0].length/2);
while(l<r){
let m=(l+r)>>1,c=0;
for(let row of a){
let x=0,y=row.length;
while(x<y){
let j=(x+y)>>1;
if(row[j]<=m)x=j+1;
else y=j
}
c+=x
}
s("Count values at most "+m,{
Matrix:a,Bounds:[l,m,r],Count:[c]
});
if(c<=k)l=m+1;
else r=m
}
return l
};

Execution canvas

Active Changed
STEP 1

Count values at most 5

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

Matrix3 rows
Bounds3 items
Count1 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

[
  [
    1,
    3,
    5
  ],
  [
    2,
    6,
    9
  ],
  [
    3,
    6,
    9
  ]
]

Execution steps

  1. Count values at most 5
  2. Count values at most 3
  3. Count values at most 4

Computed output

5
JavaScript reference implementation
const solve = (a,s)=>{
  let l=Math.min(...a.map(r=>r[0])),r=Math.max(...a.map(r=>r.at(-1))),k=Math.floor(a.length*a[0].length/2);
  while(l<r){
    let m=(l+r)>>1,c=0;
    for(let row of a){
      let x=0,y=row.length;
      while(x<y){
        let j=(x+y)>>1;
        if(row[j]<=m)x=j+1;
        else y=j
      }
      c+=x
    }
    s("Count values at most "+m,{
      Matrix:a,Bounds:[l,m,r],Count:[c]
    });
    if(c<=k)l=m+1;
    else r=m
  }
  return l
};

Continue learning

Practice related DSA questions in the same topic.