Workspace Kth Missing Positive Number
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Kth Missing Positive Number visualizer

Learn Kth Missing Positive Number with a step-by-step Binary Search visualizer, JavaScript source code and a worked example. Practice search on answer.

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
{
  "a": [
    2,
    3,
    4,
    7,
    11
  ],
  "k": 5
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
let l=0,r=a.length;
while(l<r){
let m=(l+r)>>1,missing=a[m]-m-1;
s("Count missing before midpoint",{
Array:a,Bounds:[l,m,r],Missing:[missing]
},[m]);
if(missing<k)l=m+1;
else r=m
}
return l+k
};

Execution canvas

Active Changed
STEP 1

Count missing before midpoint

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

Array5 items
Bounds3 items
Missing1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Binary Search · Search on answer

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

Execution steps

  1. Count missing before midpoint

Computed output

9
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  let l=0,r=a.length;
  while(l<r){
    let m=(l+r)>>1,missing=a[m]-m-1;
    s("Count missing before midpoint",{
      Array:a,Bounds:[l,m,r],Missing:[missing]
    },[m]);
    if(missing<k)l=m+1;
    else r=m
  }
  return l+k
};

Continue learning

Practice related DSA questions in the same topic.