Workspace Top K Frequent Elements
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Top K Frequent Elements visualizer

Learn Top K Frequent Elements with a step-by-step Heaps visualizer, JavaScript source code and a worked example. Practice priority queues and top k.

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 / 8Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    1,
    1,
    2,
    2,
    3
  ],
  "k": 2
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
let m=new Map;
for(let x of a){
m.set(x,(m.get(x)||0)+1);
s("Count occurrence",{
Frequencies:[...m].map(p=>p.join(":"))
})
}
let o=[...m].sort((a,b)=>b[1]-a[1]).slice(0,k).map(x=>x[0]);
s("Select top frequencies",{
Output:o
});
return o
};

Execution canvas

Active Changed
STEP 1

Count occurrence

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

Frequencies1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Heaps · Priority queues and top K

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,
    1,
    1,
    2,
    2,
    3
  ],
  "k": 2
}

Execution steps

  1. Count occurrence
  2. Select top frequencies

Computed output

[
  1,
  2
]
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  let m=new Map;
  for(let x of a){
    m.set(x,(m.get(x)||0)+1);
    s("Count occurrence",{
      Frequencies:[...m].map(p=>p.join(":"))
    })
  }
  let o=[...m].sort((a,b)=>b[1]-a[1]).slice(0,k).map(x=>x[0]);
  s("Select top frequencies",{
    Output:o
  });
  return o
};

Continue learning

Practice related DSA questions in the same topic.