DSAHashingFrequencies

Majority Element Visualizer

What is a Majority Element

A majority element appears more than n / 2 times. Count every value in a hash map and return the key whose count crosses that threshold. Hashing makes the count obvious; Boyer–Moore can do it in O(1) space later.

  • Threshold: more than half — ties do not count.
  • One winner: at most one value can exceed n/2.
  • Early exit: you may return as soon as a count passes the line.

How this visualizer works

Array 2, 2, 1, 1, 1, 2, 2. Watch counts climb until 2 reaches 4, which is more than 7/2.

Interactive trace

hash_table.state

Input
Hash table
Current look-up
Match / window
Stored entry

current_action

Load an input, then press Play or Step.

live_trace.py

1def majorityElement(arr):
2need = len(arr)//2
3freq = {}
4for x in arr:
5freq[x] = freq.get(x,0)+1
6if freq[x] > need:
7return x
8return None

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def majorityElement(arr):
2need = len(arr)//2
3freq = {}
4for x in arr:
5freq[x] = freq.get(x,0)+1
6if freq[x] > need:
7return x
8return None

complexity.md

OperationTime
Count + checkO(n)
SpaceO(n)

Python implementation

solution.py

1def majorityElement(arr):
2 need = len(arr) // 2
3 freq = {}
4 for x in arr:
5 freq[x] = freq.get(x, 0) + 1
6 if freq[x] > need:
7 return x
8 return None