InterviewPrepKit

Home / Coding / Arrays & Hashing

Majority Element

easy Original ↗
Solving tips
  • The hash-map count is the safe default (O(n) time, O(n) space); mention it, then upgrade for the O(1)-space follow-up.
  • Boyer-Moore voting: keep one candidate and a counter, +1 on a match, -1 otherwise, and adopt a new candidate whenever the counter hits 0 — the majority survives all cancellations. O(n) time, O(1) space.
  • Alternative: after sorting, the majority always occupies the middle index nums[n//2] because its run exceeds half the array.
  • Pitfall: Boyer-Moore is correct only because a strict majority is guaranteed; without that guarantee you need a second verification pass.

Problem

Given an integer array nums of length n, return the value that appears more than ⌊n/2⌋ times. You may assume such a value always exists in the input — that guarantee is what makes the clever solutions possible.

Follow-up: solve it in linear time and O(1) space.

Examples

  • Input: nums = [3, 2, 3] → Output: 3 3 appears twice, and 2 > ⌊3/2⌋ = 1.
  • Input: nums = [2, 2, 1, 1, 1, 2, 2] → Output: 2 2 appears 4 times out of 7, and 4 > ⌊7/2⌋ = 3.
  • Input: nums = [6] → Output: 6 A single element is trivially the majority.

Constraints

  • 1 <= n <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9
  • A majority element (count > ⌊n/2⌋) is guaranteed to exist

O(n²) is borderline here; the follow-up demands O(n) time with O(1) space.

Think about it first

Hint 1 The obvious tool is a hash map of counts. What are its time and space costs?
Hint 2 If you sorted the array, where must the majority element necessarily appear? Think about what "more than half" forces.
Hint 3 Imagine pairing up each occurrence of the majority value with one occurrence of *any other* value and deleting both. Since the majority has more than half, it can't be fully cancelled. That cancellation idea, done with a single candidate and a counter, is Boyer–Moore voting.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.