Skip to main content

15. Majority Element

easyAsked at Yelp

Find the element that appears more than n/2 times in an array — Yelp uses Boyer-Moore voting to test whether candidates can find an O(1)-space majority before scaling to dominant-keyword detection across reviews.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an array nums of size n, return the majority element — the element that appears more than floor(n/2) times. You may assume that a majority element always exists.

Constraints

  • 1 <= n <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1

Input
nums = [3,2,3]
Output
3

Example 2

Input
nums = [2,2,1,1,1,2,2]
Output
2

Approaches

1. Hash count

Count occurrences and return the element with count > n/2.

Time
O(n)
Space
O(n)
const m = new Map();
for (const x of nums) m.set(x, (m.get(x) || 0) + 1);
for (const [k, v] of m) if (v > nums.length / 2) return k;

Tradeoff:

2. Boyer-Moore voting

Maintain a candidate and a count; flip candidate when count hits 0. The survivor is the majority.

Time
O(n)
Space
O(1)
function majorityElement(nums) {
  let cand = null, count = 0;
  for (const x of nums) {
    if (count === 0) cand = x;
    count += (x === cand) ? 1 : -1;
  }
  return cand;
}

Tradeoff:

Yelp-specific tips

Yelp will reframe this as recommendation work — be ready to discuss how Boyer-Moore generalizes to streaming algorithms that find the dominant cuisine tag across a city's reviews.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Majority Element and other Yelp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →