Workspace Union Of Two Sorted Arrays
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Union of Two Sorted Arrays visualizer

Learn Union of Two Sorted Arrays with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice fundamentals.

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

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,b
},s)=>{
let i=0,j=0,o=[];
while(i<a.length||j<b.length){
let x=j===b.length||i<a.length&&a[i]<=b[j]?a[i++]:b[j++];
if(o.at(-1)!==x)o.push(x);
s("Merge next distinct value",{
A:a,B:b,Union:o,Pointers:[i,j]
})
}
return o
};

Execution canvas

Active Changed
STEP 1

Merge next distinct value

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

A4 items
B3 items
Union1 items
Pointers2 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Fundamentals

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,
    2,
    2,
    4
  ],
  "b": [
    2,
    3,
    5
  ]
}

Execution steps

  1. Merge next distinct value

Computed output

[
  1,
  2,
  3,
  4,
  5
]
JavaScript reference implementation
const solve = ({
  a,b
},s)=>{
  let i=0,j=0,o=[];
  while(i<a.length||j<b.length){
    let x=j===b.length||i<a.length&&a[i]<=b[j]?a[i++]:b[j++];
    if(o.at(-1)!==x)o.push(x);
    s("Merge next distinct value",{
      A:a,B:b,Union:o,Pointers:[i,j]
    })
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.