Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Hard · Free

Find majority element — Boyer-Moore voting intuition.

FresherFundamentalsData Structures & Algorithms
Model answer

Boyer-Moore voting

java
int majority(int[] a) {
  int cand = 0, count = 0;
  for (int x : a) {
    if (count == 0) { cand = x; count = 1; }
    else if (x == cand) count++;
    else count--;
  }
  return cand; // verify if majority guaranteed
}

Cancel different pairs; surviving candidate is majority if one exists.

Second pass to verify count if not guaranteed.