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": [
5,
3,
2,
4,
1
],
"reverse": false
}
Execution steps
Count cross-half pairs
Merge halves
Computed output
8
JavaScript reference implementation
const solve = ({
a,reverse
},s)=>{
let c=0;
function f(l,r){
if(l>=r)return;
let m=(l+r)>>1;
f(l,m);
f(m+1,r);
let j=m+1;
for(let i=l;
i<=m;
i++){
while(j<=r&&a[i]>(reverse?2*a[j]:a[j]))j++;
c+=j-m-1;
s("Count cross-half pairs",{
Array:a,Count:[c],Bounds:[l,m,r]
},[i])
}
let x=l,y=m+1,o=[];
while(x<=m||y<=r)o.push(y>r||x<=m&&a[x]<=a[y]?a[x++]:a[y++]);
a.splice(l,o.length,...o);
s("Merge halves",{
Array:a,Count:[c]
})
}
f(0,a.length-1);
return c
};