easy

Majority Element

Find the value that appears in more than half the array.

1. Define the problem

Majority Element

Given an array nums of size n, return the majority element . You may assume the majority element always exists in the array. Use Boyer-Moore voting : keep a candidate and a count, incrementing the count on a match and decrementing on a mismatch — when the count hits zero, switch to a new candidate.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 5 × 104
  • -109 ≤ numsi ≤ 109
  • The majority element always exists

Example

Inputnums = [2, 2, 1, 1, 1, 2, 2]
Output2

Explanation 2 appears four times out of seven elements, more than half, so it is the majority element.

2. Know the words first

In plain terms

Majority element
The value that appears more than n/2 times in an array of length n — strictly more than half of all the elements.
Boyer-Moore voting
A trick where matching values "vote" for a candidate and mismatches "cancel out" a vote, so the true majority value always survives to the end.
3. Visualize the solution

Vote for a candidate, cancel out on mismatches

Vote for a candidate, cancel out on mismatches
Statusinit

i=0 (value 2). count=0, so candidate becomes 2, count=1.

What happens in this step

i = 0 (value 2), count = 0
count is 0, so candidate = 2

count becomes 1.
Step 1 of 5

Steps to visualize

  1. Start with no candidate and a count of 0.
  2. For each value: if count is 0, make this value the new candidate.
  3. If the value matches the candidate, increment count; otherwise decrement count.
  4. After scanning every value, the surviving candidate is the majority element.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Vote for a candidate, cancel out on mismatches
Statusinit

i=0 (value 2). count=0, so candidate becomes 2, count=1.

What happens in this step

i = 0 (value 2), count = 0
count is 0, so candidate = 2

count becomes 1.
Step 1 of 5
5. Solution

Solution

solution.tsTypeScript
function majorityElement(nums) {
  let candidate = null;
  let count = 0;

  for (const value of nums) {
    if (count === 0) {
      candidate = value;
    }

    count += value === candidate ? 1 : -1;
  }

  return candidate;
}
Time
O(n)
Space
O(1)
6. Test cases

Test cases

InputExpectedCovers
nums = [2, 2, 1, 1, 1, 2, 2]2example from the docstring
nums = [7]7smallest valid input, a single element
nums = [3, 3, 4]3majority element appears at the start rather than scattered
nums = [5, 5, 5, 5]5every element is identical
nums = [-1, -1, -1, 2, 2]-1negative values as the majority element
nums = [1, 1, 2, 1, 2]1majority just barely exceeds half the array