Majority Element solution explained

The majority element, the value that fills more than half of an array, can be found in O(n) time and O(1) space with the Boyer-Moore voting algorithm: keep one candidate and a counter, add one when the next value matches the candidate, subtract one when it does not, and switch candidates whenever the counter is zero. When a majority is guaranteed, the final candidate is the answer; when it is not, a second pass confirms it.

By Published 7 min read

The problem

Given a non-empty list of integers, return the value that occurs more than half the time. Note the strict inequality: in a list of six values, the majority must appear at least four times. The standard statement guarantees that such a value exists, and the interesting follow-up is to solve it with constant extra memory.

Example arrays for this page
ArrayMajorityCount
[6, 2, 6, 6, 9]63 of 5
[4]41 of 1
[-1, -1, 3, -1, 3, -1, 8]-14 of 7
[1, 2, 1, 2]NoneEach value has exactly half, which is not more than half
Example arrays for this page. Scroll sideways on a small screen.

What it reveals

Almost everyone solves this with a dictionary. The question is a check on whether you know, or can reason your way to, the voting algorithm, and whether you can explain why it works instead of reciting it. It also tests care with assumptions: candidates who forget that voting can return a wrong value when no majority exists lose points even if their code passes the guaranteed cases.

Common extensions

  • No majority is promised; return none if there is none. Run the vote, then count the candidate in a second pass.
  • Return every value that appears more than n / 3 times. There can be at most two. Keep two candidates and two counters. Code below.
  • The data is split across machines. Voting results do not merge simply, but counts per candidate do: each machine reports its candidate, then all machines count the few candidates.
  • More than n / k times. Keep k - 1 candidates, the Misra-Gries generalization, then verify.

Counting and sorting

Counting every value with a hash map and returning the most common one is O(n) time and O(n) space. Sorting and returning the middle element also works when a majority exists: a value that fills more than half the positions must cover the middle index, so it is O(n log n) time and no map at all. Both are fair opening answers.

from collections import Counter


def majority_by_counting(nums):
    counts = Counter(nums)
    return max(counts, key=counts.get)
Count with a Counter. O(n) time, O(n) space.

Boyer-Moore voting

Walk the array with a candidate and a lead counter. When the lead is zero, the current value becomes the candidate. A matching value increases the lead; any other value decreases it. Think of each decrease as cancelling one candidate copy against one different value. The majority has more copies than every other value combined, so it cannot be cancelled out entirely; it is the value left standing at the end.

def majority_element(nums):
    candidate, lead = None, 0
    for x in nums:
        if lead == 0:
            candidate = x          # start a new run with x in front
        lead += 1 if x == candidate else -1
    return candidate
Voting with one candidate. O(n) time, O(1) space. Assumes a majority exists.

Trace [-1, -1, 3, -1, 3, -1, 8]: the lead goes 1, 2, 1, 2, 1, 2, 1 with -1 as the candidate throughout, so -1 is returned. On [1, 2, 3] the candidate ends as 3 with a lead of 1, but 3 is not a majority, which is why the guarantee matters.

Voting with a check, in JavaScript

If the input might have no majority, add a second pass that counts the candidate and compare against half the length. It stays O(n) time and O(1) space, and it turns a promise you were given into a fact your code checks.

function majorityOrNull(nums) {
  let candidate = null;
  let lead = 0;
  for (const x of nums) {
    if (lead === 0) candidate = x;
    lead += x === candidate ? 1 : -1;
  }
  // Second pass: only needed when a majority is not promised.
  let seen = 0;
  for (const x of nums) if (x === candidate) seen++;
  return seen * 2 > nums.length ? candidate : null;
}
Vote, then verify. Returns null when no value fills more than half.

More than a third

At most two values can each appear more than n / 3 times. Keep two candidates with their own counters. A value that matches either candidate raises that counter. If it matches neither and a counter is zero, it takes that slot. Otherwise it cancels one copy of each candidate. Then count both candidates to confirm, since this version never comes with a guarantee.

def more_than_a_third(nums):
    first, second = None, None
    count1 = count2 = 0
    for x in nums:
        if x == first:
            count1 += 1
        elif x == second:
            count2 += 1
        elif count1 == 0:
            first, count1 = x, 1
        elif count2 == 0:
            second, count2 = x, 1
        else:
            count1 -= 1        # x cancels one copy of each candidate
            count2 -= 1
    limit = len(nums) // 3
    return [c for c in (first, second)
            if c is not None and nums.count(c) > limit]
Two candidates, then a counting pass. [5, 5, 2, 2, 8, 5, 2] gives 5 and 2.

The order of the checks matters: compare with both candidates before claiming an empty slot, or the same value can end up held in both slots.

Complexity

n values in the input
ApproachTimeExtra spaceNeeds the guarantee
Hash map of countsO(n)O(n)No
Sort, take the middleO(n log n)O(1) to O(n)Yes, or verify after
VotingO(n)O(1)Yes
Voting plus a counting passO(n)O(1)No
n values in the input. Scroll sideways on a small screen.

Cases to test

  • One element.
  • The majority at the very start, the very end, or spread evenly.
  • Negative values.
  • An exact half split such as [1, 2, 1, 2], which has no majority.
  • Arrays where the vote's candidate changes several times before settling.

Frequent mistakes

  • Returning the candidate without verification when the problem does not promise a majority.
  • Taking a new candidate but forgetting to count its own first copy, so it starts a vote behind.
  • Using greater than or equal to n / 2 instead of strictly greater than.
  • In the n / 3 version, checking for an empty slot before checking both candidates.
  • Explaining voting as a frequency count. It is not; the final lead says nothing about how often the value appears.

Putting it into words

Fictional example

Explaining why voting works
Candidate
A hash map works in linear time, but I can drop the extra space with a vote.
Candidate
I keep a candidate and a lead. Same value, plus one. Different value, minus one. When the lead hits zero, the next value takes over.
Candidate
Every minus one pairs a candidate copy with a different value. The majority has more copies than everything else together, so it can't be paired away completely.
Interviewer
What if there's no majority?
Candidate
Then the candidate might be anything, so I'd count it in a second pass and only return it if it's more than half.

Move Zeroes and Rotate Array are other single-pass, constant-space array exercises. First Missing Positive replaces a hash set with the array itself. For the counting side of frequency questions, see Top K Frequent Elements.

Rehearsing with Natively

Natively can pick up a problem like this from a screenshot, or from the page through its Chrome extension, and explain the voting idea with code in an overlay on Mac or Windows. That is useful when you can write the loop but cannot yet say why it works. Rehearse the explanation aloud and the transcript shows whether you mentioned the verification pass. See Natively for coding interviews.

Questions people ask

What is the Boyer-Moore voting algorithm?

A single pass with a candidate and a counter. A matching value adds one, a different value subtracts one, and a zero counter makes the next value the candidate. If a majority exists, it is the final candidate.

Why does sorting find the majority element?

A value that fills more than half the positions must cover the middle index after sorting, so nums[n // 2] is the majority. It costs O(n log n).

What if there is no majority element?

Voting still returns some candidate, which may be wrong. Count that candidate in a second pass and return it only if it appears more than n / 2 times.

How do you find elements that appear more than n/3 times?

At most two such values exist. Keep two candidates with two counters, cancel against both when a value matches neither, then count both candidates to confirm.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP