Worked example and algorithm walkthrough
Topic: Arrays · Optimization and matrix
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,
0,
-1,
0,
-2,
2
],
"k": 0,
"n": 4
}Execution steps
- Compare remaining pair
Computed output
[
[
-2,
-1,
1,
2
],
[
-2,
0,
0,
2
],
[
-1,
0,
0,
1
]
]JavaScript reference implementation
const solve = ({
a,k,n
},s)=>{
a.sort((x,y)=>x-y);
let o=[];
function f(start,k,n,p){
if(n===2){
let l=start,r=a.length-1;
while(l<r){
let t=a[l]+a[r];
s("Compare remaining pair",{
Array:a,Prefix:p,Matches:o
},[l,r]);
if(t===k){
o.push([...p,a[l],a[r]]);
let x=a[l],y=a[r];
while(l<r&&a[l]===x)l++;
while(l<r&&a[r]===y)r--
}else if(t<k)l++;
else r--
}
return
}
for(let i=start;
i<=a.length-n;
i++)if(i===start||a[i]!==a[i-1])f(i+1,k-a[i],n-1,[...p,a[i]])
}
f(0,k,n,[]);
return o
};