The problem. Given an array nums of size n, return the majority element — the value that appears more than n / 2 times. You may assume a majority element always exists.
Input: nums = [3, 2, 3]
Output: 3
Input: nums = [2, 2, 1, 1, 1, 2, 2]
Output: 2"More than half" is a strong promise: the majority value outnumbers all the other values put together. Keep that sentence in mind — the best solution is built entirely on it.
For each element, count how many times it appears by scanning the whole array. The first one whose count passes n / 2 is the answer.
function majorityElement(nums) { for (const x of nums) { let count = 0; for (const y of nums) if (y === x) count++; if (count > nums.length / 2) return x; }}Time O(n²), space O(1). The same values get counted over and over.
Keep a running count per value in a hash map. As soon as a count passes n / 2, that value is the majority.
function majorityElement(nums) { const counts = new Map(); for (const x of nums) { counts.set(x, (counts.get(x) ?? 0) + 1); if (counts.get(x) > nums.length / 2) return x; }}Time O(n), space O(n). One pass — but the map can hold up to n/2 different values. (Sorting and taking the middle element also works, since the majority must cover the middle, but that costs O(n log n).)
Imagine every element is a voter. Pair up two different values and remove them both — one majority vote and one other vote cancel. Because the majority has more votes than everyone else combined, it can never be cancelled completely: whatever survives at the end must be the majority.
The cancelling takes one pass and two variables, a candidate and its count:
count is 0, nobody is ahead — the current value becomes the new candidate.count goes up by one (a supporting vote).count goes down by one (a vote cancelled).Try [1, 3, 3, 2, 3, 3, 3], where the majority only takes over late. With no majority at all, you'll see why the problem's guarantee matters.
Time O(n), space O(1). One pass, two variables.
O(n²)Each of the n values is counted by scanning the whole array again.
O(1)Just a counter.
O(n)[5] returns 5.[1, 3, 3, 2, 3, 3, 3].The follow-up "find every value that appears more than n / 3 times" uses the same cancelling idea with two candidates and two counts — at most two values can pass n / 3.
One pass, and each count update is O(1) on average.
O(n)The map can hold up to n/2 different values.
O(n)One pass; each element adds or removes one vote.
O(1)Only two variables: the candidate and its count.