DSA Tracker

Problem

Medium

Majority Element II

A medium Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Arrays
Sheets
1
Core for
26 roles

The problem

Find all elements in the array that appear more than n/3 times, where n is the array length.

Example 1

Input
[7,3,7]
Output
[7]

Example 2

Input
[1,1,1,3,3,2,2,2]
Output
[1,2]

Example 3

Input
[1]
Output
[1]

Constraints

  • 1 <= n <= 5*10^4
  • -10^9 <= arr[i] <= 10^9

How to think about it

Updated 2026-09-29

There can be at most two distinct elements that appear strictly more than n / 3 times. Canceling out three mutually distinct elements simultaneously reduces the size of the array without changing which elements hold a strict majority threshold, allowing Boyer-Moore voting to track at most two candidates at once.

Approaches, worst first

  1. Frequency hash map

    time O(n) · space O(n)

    Count frequencies of every distinct number using a hash map, then collect every key whose count strictly exceeds floor(n / 3). Unconditionally correct, but allocates memory proportional to the number of distinct elements.

  2. Extended Boyer-Moore votingWrite this one

    time O(n) · space O(1)

    Maintain two candidate variables and two vote counters. If a number matches a candidate, increment its count; if a counter hits 0, assign the new number; otherwise decrement both counters. A final verification pass checks whether each candidate actually exceeds n / 3.

Where people lose marks · 3
  • Failing to run the second verification pass to validate candidates, which returns false positives on arrays where no element exceeds the n / 3 frequency threshold.
  • Assigning candidate2 the same value as candidate1 when initializing or resetting counters.
  • Checking counter equality to zero before checking if the incoming element matches the other candidate, splitting votes across identical candidates.

Full solution

Extended Boyer-Moore voting with two candidates: at most two values can appear more than n/3 times, so two counters plus one verification pass give O(n) time in O(1) extra space, which the hash-map count cannot.

Python
def majority_element(nums: list[int]) -> list[int]:
    # At most two values can exceed n/3, so two Boyer-Moore candidates suffice.
    cand1, cand2 = None, None
    count1, count2 = 0, 0
    for x in nums:
        if x == cand1:
            count1 += 1
        elif x == cand2:
            count2 += 1
        elif count1 == 0:
            cand1, count1 = x, 1
        elif count2 == 0:
            cand2, count2 = x, 1
        else:
            count1 -= 1
            count2 -= 1
    # Candidates are only possible majorities; verify with a real count.
    threshold = len(nums) // 3
    return [c for c in (cand1, cand2) if c is not None and nums.count(c) > threshold]
JavaScript
function majorityElement(nums) {
  // At most two values can exceed n/3, so two Boyer-Moore candidates suffice.
  let cand1 = null, cand2 = null;
  let count1 = 0, count2 = 0;
  for (const x of nums) {
    if (x === cand1) count1++;
    else if (x === cand2) count2++;
    else if (count1 === 0) { cand1 = x; count1 = 1; }
    else if (count2 === 0) { cand2 = x; count2 = 1; }
    else { count1--; count2--; }
  }
  // Candidates are only possible majorities; verify with a real count.
  const threshold = Math.floor(nums.length / 3);
  return [cand1, cand2].filter(
    (c) => c !== null && nums.filter((v) => v === c).length > threshold,
  );
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

More Arrays problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .