Workspace Majority Element Ii
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Majority Element II visualizer

Learn Majority Element II with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice hashing and prefix sums.

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
[
  1,
  2,
  1,
  3,
  1,
  2,
  2
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let m=new Map;
for(let x of a){
if(m.has(x))m.set(x,m.get(x)+1);
else if(m.size<2)m.set(x,1);
else for(let [k,v] of m){
if(v===1)m.delete(k);
else m.set(k,v-1)
}
s("Cancel groups of three",{
Array:a,Candidates:[...m].map(p=>p.join(":"))
})
}
return [...m.keys()].filter(x=>a.filter(y=>y===x).length>a.length/3).sort((x,y)=>x-y)
};

Execution canvas

Active Changed
STEP 1

Cancel groups of three

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

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

Worked example and algorithm walkthrough

Topic: Arrays · Hashing and prefix sums

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

[
  1,
  2,
  1,
  3,
  1,
  2,
  2
]

Execution steps

  1. Cancel groups of three

Computed output

[
  1,
  2
]
JavaScript reference implementation
const solve = (a,s)=>{
  let m=new Map;
  for(let x of a){
    if(m.has(x))m.set(x,m.get(x)+1);
    else if(m.size<2)m.set(x,1);
    else for(let [k,v] of m){
      if(v===1)m.delete(k);
      else m.set(k,v-1)
    }
    s("Cancel groups of three",{
      Array:a,Candidates:[...m].map(p=>p.join(":"))
    })
  }
  return [...m.keys()].filter(x=>a.filter(y=>y===x).length>a.length/3).sort((x,y)=>x-y)
};

Continue learning

Practice related DSA questions in the same topic.