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

Majority Element visualizer

Learn Majority Element 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
[
  2,
  2,
  1,
  1,
  1,
  2,
  2
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let v=0,c=0;
a.forEach((x,i)=>{
if(!c)v=x;
c+=x===v?1:-1;
s("Cancel unequal votes",{
Array:a,Candidate:[v],Votes:[c]
},[i])
});
return a.filter(x=>x===v).length>a.length/2?v:null
};

Execution canvas

Active Changed
STEP 1

Cancel unequal votes

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

Array7 items
Candidate1 items
Votes1 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

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

Execution steps

  1. Cancel unequal votes

Computed output

2
JavaScript reference implementation
const solve = (a,s)=>{
  let v=0,c=0;
  a.forEach((x,i)=>{
    if(!c)v=x;
    c+=x===v?1:-1;
    s("Cancel unequal votes",{
      Array:a,Candidate:[v],Votes:[c]
    },[i])
  });
  return a.filter(x=>x===v).length>a.length/2?v:null
};

Continue learning

Practice related DSA questions in the same topic.