Skip to main content

22. Majority Element

easyAsked at Ola

Find the element that appears more than n/2 times in an array.

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

Problem

Given an array nums of size n, return the majority element. The majority element is the element that appears more than n/2 times; you may assume that the majority element always exists.

Constraints

  • n == nums.length
  • 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 first that exceeds 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);
  if (m.get(x) > nums.length/2) return x;
}

Tradeoff:

2. Boyer-Moore voting

Maintain a candidate and a count; flip candidate when count drops to zero. O(1) space.

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

Tradeoff:

Ola-specific tips

Ola interviewers love the Boyer-Moore tradeoff; tie it to picking the dominant driver-region label in a streaming heartbeat sample.

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

Practice these live with InterviewChamp.AI →