Skip to main content

8. Majority Element

easyAsked at JetBrains

Find the element that appears more than n/2 times — JetBrains uses this to test whether you can collapse counters in constant space using the Boyer-Moore vote.

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

Problem

Given an array of size n, return the majority element — the element appearing more than n/2 times. You may assume a majority element always exists.

Constraints

  • 1 <= nums.length <= 5 * 10^4
  • Majority element always exists

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 every element and pick the most frequent.

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

Tradeoff:

2. Boyer-Moore vote

Maintain a candidate and a vote counter that decrements on disagree, increments on agree. Linear time, constant memory — JetBrains values that streaming budget.

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

Tradeoff:

JetBrains-specific tips

JetBrains expects you to articulate the invariant in plain English — they want to know you can collapse counters the same way their inspection engines summarize bulk PSI traversal results.

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

Practice these live with InterviewChamp.AI →