Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Algorithms
Algorithmsmedium

Boyer–Moore majority vote: what does it solve and what’s the core idea?

Tags
#majority-vote#array#linear-time#constant-space
Back to categoryPractice quiz

Answer

It finds the element that appears more than n/2 times (if it exists). The idea is to cancel pairs of different elements; the remaining candidate is the majority. It runs in O(n) time and O(1) space.

function majority(nums: number[]): number {
  let cand = 0;
  let count = 0;
  for (const x of nums) {
    if (count === 0) cand = x;
    count += x === cand ? 1 : -1;
  }
  return cand;
}

Advanced answer

Deep dive

Expanding on the short answer — what usually matters in practice:

  • Context (tags): majority-vote, array, linear-time, constant-space
  • Complexity: compare typical operations (average vs worst-case).
  • Invariants: what must always hold for correctness.
  • When the choice is wrong: production symptoms (latency, GC, cache misses).
  • Explain the "why", not just the "what" (intuition + consequences).
  • Trade-offs: what you gain/lose (time, memory, complexity, risk).
  • Edge cases: empty inputs, large inputs, invalid inputs, concurrency.

Examples

Here’s an additional example (building on the short answer):

function majority(nums: number[]): number {
  let cand = 0;
  let count = 0;
  for (const x of nums) {
    if (count === 0) cand = x;
    count += x === cand ? 1 : -1;
  }
  return cand;
}

Common pitfalls

  • Too generic: no concrete trade-offs or examples.
  • Mixing average-case and worst-case (e.g., complexity).
  • Ignoring constraints: memory, concurrency, network/disk costs.

Interview follow-ups

  • When would you choose an alternative and why?
  • What production issues show up and how do you diagnose them?

Related questions

Algorithms
What does Kadane’s algorithm solve?
#kadane#dynamic-programming#array
Algorithms
What is the two pointers technique?
#two-pointers#array#technique
Data Structures
Difference between Array and LinkedList?
#array#linked-list
  • How would you test edge cases?
  • #comparison