Majority Element

EasyArrays · Voting / Counting🧩 Array ManipulationLeetCode #169 ↗Updated

Problem

You are given an integer array nums of length n. Exactly one value appears more than ⌊n/2⌋ times (the input guarantees it exists). Return that majority value.
Input[3,2,3]Output3
Input[2,2,1,1,1,2,2]Output2

1 ≤ n ≤ 5·104  ·  -109 ≤ nums[i] ≤ 109  ·  majority always exists  ·  Follow-up: O(n) time, O(1) space.

Try it yourself

Java
class Solution {
    public int majorityElement(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Pair each majority element with a different element and cancel both out — the majority has more copies than all other values combined, so it is the one left standing.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceCount Every Candidate

Time O(n2)Space O(1)

Treat each nums[i] as a candidate and count its occurrences with a second scan. The first value whose count exceeds n/2 is the answer.

Java
public int majorityElement(int[] nums) {
    int n = nums.length;
    for (int i = 0; i < n; i++) {
        int count = 0;
        for (int j = 0; j < n; j++) {
            if (nums[j] == nums[i]) count++;
        }
        if (count > n / 2) return nums[i];
    }
    return -1; // unreachable: a majority is guaranteed
}

Trivial and memory-free, but quadratic — too slow for n = 5·104.

At a glance

LevelApproachTimeSpace
Brute ForceCount Every CandidateO(n2)O(1)
BetterHash Map FrequencyO(n)O(n)
OptimalBoyer–Moore VotingO(n)O(1)
Common pitfalls
  • Using ≥ n/2 instead of > n/2 — wrong for even n.
  • Switching candidate after decrementing — check count == 0 first.
  • Assuming the Boyer–Moore result is valid without a guarantee — verify it.
Interview tips
  • Mention sorting + nums[n/2] as a quick O(n log n) one-liner.
  • Explain Boyer–Moore as “pairwise cancellation”, not just code.
  • Extend: Majority Element II (> n/3) keeps two candidates.
Pattern
Boyer–Moore voting → find a value occurring more than n/k times in O(1) extra space.
My notes saved in this browser