Learn Subarrays with K Different Integers with a step-by-step Sliding Window & Two Pointers visualizer, JavaScript source code and a worked example. Practice fixed and variable windows.
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.
Topic: Sliding Window & Two Pointers · Fixed and variable windows
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,
1,
2,
3
],
"k": 2
}
Execution steps
Count windows with at most 2
Count windows with at most 1
Computed output
7
JavaScript reference implementation
const solve = ({
a,k
},s)=>{
function atMost(k){
let l=0,c=0,m=new Map;
for(let r=0;
r<a.length;
r++){
m.set(a[r],(m.get(a[r])||0)+1);
while(m.size>k){
let x=a[l++];
m.set(x,m.get(x)-1);
if(!m.get(x))m.delete(x)
}
c+=r-l+1;
s("Count windows with at most "+k,{
Array:a,Bounds:[l,r],Count:[c]
})
}
return c
}
return atMost(k)-atMost(k-1)
};