Workspace Merge K Sorted Arrays
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Merge K Sorted Arrays visualizer

Learn Merge K Sorted Arrays with a step-by-step Heaps visualizer, JavaScript source code and a worked example. Practice priority queues and top k.

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

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let o=[],p=a.map(()=>0);
while(true){
let b=-1;
for(let i=0;
i<a.length;
i++)if(p[i]<a[i].length&&(b<0||a[i][p[i]]<a[b][p[b]]))b=i;
if(b<0)break;
o.push(a[b][p[b]++]);
s("Choose smallest remaining head",{
Lists:a,Positions:p,Merged:o
})
}
return o
};

Execution canvas

Active Changed
STEP 1

Choose smallest remaining head

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

Lists3 rows
Positions3 items
Merged1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Heaps · Priority queues and top K

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,
    4,
    5
  ],
  [
    1,
    3,
    4
  ],
  [
    2,
    6
  ]
]

Execution steps

  1. Choose smallest remaining head

Computed output

[
  1,
  1,
  2,
  3,
  4,
  4,
  5,
  6
]
JavaScript reference implementation
const solve = (a,s)=>{
  let o=[],p=a.map(()=>0);
  while(true){
    let b=-1;
    for(let i=0;
    i<a.length;
    i++)if(p[i]<a[i].length&&(b<0||a[i][p[i]]<a[b][p[b]]))b=i;
    if(b<0)break;
    o.push(a[b][p[b]++]);
    s("Choose smallest remaining head",{
      Lists:a,Positions:p,Merged:o
    })
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.