Skip to main content

12. Majority Element

easyAsked at Riot Games

Find the element that appears more than n/2 times — Boyer-Moore voting is a Riot favorite because it surfaces dominant patterns in chat-spam and anti-cheat telemetry.

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

Problem

Given an array nums of size n, return the element that appears more than n/2 times. You may assume that the 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 map count

Tally every element and return the one exceeding n/2.

Time
O(n)
Space
O(n)
const c = new Map();
for (const n of nums) {
  c.set(n, (c.get(n)||0)+1);
  if (c.get(n) > nums.length/2) return n;
}

Tradeoff:

2. Boyer-Moore voting

Maintain a candidate and a count; increment when matching and decrement otherwise. Riot likes how the running tally maps onto streaming anti-cheat heuristic counters.

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

Tradeoff:

Riot Games-specific tips

Riot grades for streaming-friendly solutions — Boyer-Moore's O(1) state mirrors how their anti-cheat heuristics keep a single dominant-signal counter per match without per-player allocations.

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 Riot Games interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →