Worked example and algorithm walkthrough
Topic: Stacks & Queues · Monotonic structures
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
{
"capacity": 2,
"ops": [
[
"put",
1,
1
],
[
"put",
2,
2
],
[
"get",
1
],
[
"put",
3,
3
],
[
"get",
2
],
[
"get",
3
],
[
"put",
4,
4
],
[
"get",
4
]
],
"lfu": true
}Execution steps
- Execute put 1
- Execute put 2
- Execute get 1
- Execute put 3
- Execute get 2
- Execute get 3
- Execute put 4
- Execute get 4
Computed output
[ 1, -1, 3, 4 ]
JavaScript reference implementation
const solve = ({
capacity,ops,lfu
},s)=>{
let m=new Map,o=[],t=0;
for(let [op,k,v] of ops){
t++;
if(op==="get"){
let x=m.get(k);
o.push(x?x.v:-1);
if(x){
x.f++;
x.t=t
}
}else if(m.has(k)){
let x=m.get(k);
x.v=v;
x.f++;
x.t=t
}else{
if(m.size===capacity){
let q=[...m].sort((a,b)=>(lfu?a[1].f-b[1].f:0)||a[1].t-b[1].t)[0];
m.delete(q[0])
}
m.set(k,{
v,f:1,t
})
}
s("Execute "+op+" "+k,{
Cache:[...m].map(([k,x])=>k+":"+x.v+" f="+x.f+" t="+x.t),Output:o
})
}
return o
};