Majority Element II solution explained

To find every value that appears more than n/3 times, note that there can be at most two such values. Keep two candidates with counters: a matching value raises its counter, an empty slot takes the new value, and any other value lowers both counters. A second pass counts the two survivors and keeps those above n/3. That uses O(n) time and O(1) extra space, while a simple count table uses O(n) space.

By Published 6 min read

The task, restated

You get a list of n integers. Return every distinct value whose number of occurrences is strictly greater than n divided by 3, rounded down. The result can be empty, hold one value or hold two. Order does not matter. The interesting part is the follow-up: can you do it without memory that grows with the input?

Examples made up for this walkthrough
ValuesThreshold (more than)Answer
[4, 1, 4, 2, 1, 4, 1]2[4, 1], each appears 3 times
[6, 6, 7]1[6]
[1, 2, 3, 4]1[], nothing repeats
[9]0[9]
[3, 3, 8, 8, 5, 5]2[], each appears exactly twice, which is not more than 2
Examples made up for this walkthrough. Scroll sideways on a small screen.

Why there are at most two answers

If three different values each appeared more than n/3 times, together they would fill more than n slots, which is impossible. So the answer has at most two values. That fact is what makes a constant-space method possible: you only ever need to track two candidates.

What the interviewer is listening for

Most interviewers accept the counting answer at first and then ask for O(1) space. They want to see whether you know, or can reason your way to, the voting idea, and whether you remember the verification pass. Skipping that second pass is the most common failure, because the survivors of the vote are only candidates, not answers.

First answer: count everything

from collections import Counter

def frequent_thirds_counting(values):
    limit = len(values) // 3
    return [v for v, c in Counter(values).items() if c > limit]
Count table, O(n) time and O(n) space. Also the reference for tests.

Sorting and scanning for long runs also works in O(n log n) time. Mention it if you like, but counting is the simpler first answer.

Optimal: two candidates that cancel out others

Think of it as removing triples of three different values. Each time you meet a value that matches neither candidate while both counters are positive, you throw away one copy of each candidate and the new value: three distinct values gone together. A value that appears more than n/3 times cannot be fully cancelled this way, because each cancellation uses up only one of its copies along with two others. So any real answer must still be a candidate at the end.

  1. MatchIf the value equals candidate one, increase counter one. Else if it equals candidate two, increase counter two.
  2. Fill an empty slotElse if counter one is zero, make this value candidate one with count 1. Else if counter two is zero, do the same for slot two.
  3. CancelOtherwise decrease both counters by one.
  4. VerifyCount how often each surviving candidate really appears and keep those above n/3.

The order of the checks matters. Test both matches before filling an empty slot, or a value already held in slot two could be copied into slot one as well.

def frequent_thirds(values):
    first, second = None, None
    count1, count2 = 0, 0
    for v in values:
        if v == first:
            count1 += 1
        elif v == second:
            count2 += 1
        elif count1 == 0:
            first, count1 = v, 1
        elif count2 == 0:
            second, count2 = v, 1
        else:
            count1 -= 1
            count2 -= 1
    limit = len(values) // 3
    result = []
    for candidate in (first, second):
        if candidate is not None and candidate not in result:
            if values.count(candidate) > limit:
                result.append(candidate)
    return result
Python: two-candidate vote plus verification, O(n) time, O(1) extra space.
function frequentThirds(values) {
  let first = null, second = null;
  let count1 = 0, count2 = 0;
  for (const v of values) {
    if (v === first) count1++;
    else if (v === second) count2++;
    else if (count1 === 0) { first = v; count1 = 1; }
    else if (count2 === 0) { second = v; count2 = 1; }
    else { count1--; count2--; }
  }
  const limit = Math.floor(values.length / 3);
  const result = [];
  for (const c of [first, second]) {
    if (c === null || result.includes(c)) continue;
    let seen = 0;
    for (const v of values) if (v === c) seen++;
    if (seen > limit) result.push(c);
  }
  return result;
}
JavaScript: the same vote, with a counting loop for verification.

A short trace on [4, 1, 4, 2, 1, 4, 1]: 4 fills slot one, 1 fills slot two, 4 raises slot one to 2, 2 cancels both (1 and 0), 1 matches slot two again (its counter goes from 0 back to 1), 4 raises slot one to 2, and 1 raises slot two to 2. The candidates are 4 and 1, and the verification pass confirms both appear 3 times, which is more than 2.

Cost of each approach

n is the length of the list
ApproachTimeExtra space
Count tableO(n)O(n)
Sort, then scan runsO(n log n)O(1) to O(n), depending on the sort
Two-candidate vote plus verificationO(n), two passesO(1)
n is the length of the list. Scroll sideways on a small screen.

The same idea generalizes: to find values that appear more than n/k times, keep k - 1 candidates. Interviewers sometimes ask about that, and the answer is O(n·k) time with O(k) space.

Edge cases to test

  • An empty list: return an empty result.
  • One value: it is always an answer.
  • Values tied exactly at n/3, which must not be included.
  • Two answers, as in the first example.
  • One value filling the whole list, so slot two may stay empty.
  • Negative numbers and zero, which matter if you used 0 as the empty marker.

Common mistakes

  • Skipping the verification pass and returning both candidates.
  • Checking for an empty slot before checking for a match, which can put the same value in both slots.
  • Using 0 or -1 as the empty marker when such values can appear in the input.
  • Using >= instead of > against the threshold.
  • Calling the count table O(1) space because the answer has at most two values.

How to explain it out loud

Fictional example

Explaining the vote without hand-waving
Candidate
A dictionary of counts gives linear time, but you asked for constant space. First, at most two values can exceed a third, since three would need more than n slots.
Candidate
So I track two candidates with counters. A different value with both slots full cancels one of each, which removes three distinct values at once. A true answer cannot be fully cancelled, so it survives as a candidate.
Candidate
Survivors are only candidates, so I make a second pass to count them. Two passes, O(n) time, constant extra space.

H-Index is another counting problem where the trick is knowing which counts matter. Top K Frequent Elements starts from the same count table and asks for the most common values instead of those above a threshold. Find Pivot Index is a lighter single-pass warm-up. The full list is on the coding problems hub.

Rehearsing it with Natively

The vote is easy to code from memory and hard to justify on the spot, so practice the justification. In a mock round on Mac or Windows, Natively can read the problem from a screenshot and give a code hint if you stall, and its transcript lets you check whether you explained why survivors are only candidates. The coding interview assistant page covers the details.

Questions people ask

How many elements can appear more than n/3 times?

At most two. Three different values each above n/3 would need more than n positions in total.

How do you solve Majority Element II in O(1) space?

Keep two candidates with counters. Matches raise a counter, an empty slot takes a new value, and any other value lowers both counters. Then count the two survivors and keep those above n/3.

Why is a second pass needed?

The vote only guarantees that any real answer is among the survivors. A survivor may still fall short of the threshold, so you must count it.

Can this be extended to n/k?

Yes. Keep k - 1 candidates and counters, then verify each one. That takes O(n·k) time and O(k) extra space.

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