Workspace Insert Interval
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Insert Interval visualizer

Learn Insert Interval with a step-by-step Greedy & Intervals visualizer, JavaScript source code and a worked example. Practice scheduling and resource allocation.

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

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,b
},s)=>{
let o=[],i=0;
while(i<a.length&&a[i][1]<b[0])o.push(a[i++]);
while(i<a.length&&a[i][0]<=b[1]){
b=[Math.min(b[0],a[i][0]),Math.max(b[1],a[i][1])];
i++;
s("Merge overlapping insertion",{
Input:a,Pending:b,Output:o
})
}
o.push(b,...a.slice(i));
s("Append remaining intervals",{
Output:o
});
return o
};

Execution canvas

Active Changed
STEP 1

Merge overlapping insertion

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

Input2 rows
Pending2 items
Output0 items

Empty at this step.

Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Greedy & Intervals · Scheduling and resource allocation

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

Execution steps

  1. Merge overlapping insertion
  2. Append remaining intervals

Computed output

[
  [
    1,
    5
  ],
  [
    6,
    9
  ]
]
JavaScript reference implementation
const solve = ({
  a,b
},s)=>{
  let o=[],i=0;
  while(i<a.length&&a[i][1]<b[0])o.push(a[i++]);
  while(i<a.length&&a[i][0]<=b[1]){
    b=[Math.min(b[0],a[i][0]),Math.max(b[1],a[i][1])];
    i++;
    s("Merge overlapping insertion",{
      Input:a,Pending:b,Output:o
    })
  }
  o.push(b,...a.slice(i));
  s("Append remaining intervals",{
    Output:o
  });
  return o
};

Continue learning

Practice related DSA questions in the same topic.