Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Coding Interview Patterns  Module 3 – Arrays and hashing

Majority vote in O(1) space

Find the value that fills more than half of a list with O(1) extra memory using the Boyer–Moore vote, check it, and extend it to more than a third.

  • Intermediate
  • 20 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free intro, Pro: 5 of 20 minutes free
Free: The problem: an outright winner from a ballot box. With a pass: the other 9 sections and 3 interview answers, about 15 minutes.

What you will learn

  • Find a majority value with the Boyer–Moore vote in O(n) time and O(1) extra memory
  • Check the candidate with a second pass when a majority is not promised
  • Prove why a value with more than half of the items survives the cancellations
  • Extend the vote to values that fill more than a third of the items
  • Choose between counting, sorting and voting for a given memory limit

Before you start

What you’ll learn · Before you start

What you will learn

  • Find a majority value with the Boyer–Moore vote in O(n) time and O(1) extra memory
  • Check the candidate with a second pass when a majority is not promised
  • Prove why a value with more than half of the items survives the cancellations
  • Extend the vote to values that fill more than a third of the items
  • Choose between counting, sorting and voting for a given memory limit

Before you start

On this page

A majority element: A value that fills more than half of a list, such as 4 in [4, 7, 4, 4, 2, 4]. A list has at most one, and exactly half is not enough. fills more than half of a list, as member 4 fills four of the six ballots [4, 7, 4, 4, 2, 4], and the Boyer–Moore vote finds it in one pass with two variables: a candidate and a counter. The vote pairs off items with different values, and because a majority value outnumbers all the others together, some of its items are never paired and it ends as the candidate. A second pass counts the candidate, since a list without a majority still produces one. The whole method takes O(n) time and O(1) extra memory, where counting every value needs a map as large as the number of distinct values. The problem usually called majority element appears here as an original ballot-box version, with its limits, and the obvious counts turn out too slow or too large.

The problem: an outright winner from a ballot box

The problem

A club elects its captain. Each ballot holds the member number of one candidate, and the ballots are read from the box one at a time, in no particular order. A candidate wins outright with more than half of the ballots. Return the winner’s member number, or −1 if nobody has more than half. The counting machine may read the ballots twice but can store only a handful of numbers, however many ballots there are. Limits: 1 to 10⁷ ballots, member numbers from 1 to 10⁹.

  1. [4, 7, 4, 4, 2, 4] gives 4: four of six ballots.
  2. [3, 3, 5, 5] gives −1: two of four is exactly half, not more.
  3. [9] gives 9.
Four ballots for 4 above two other ballots, 7 and 2; each of those is paired with one ballot for 4, and two ballots for 4 are left over.444(left over)4(left over)72pairedpaired

A majority survives the pairing

Text description of the diagram

The box holds six ballots: four for member 4 and one each for members 7 and 2.

  • The ballot for 7 is paired with one ballot for 4, and the ballot for 2 with another.
  • Two ballots for 4 are left over, because 4 has more ballots than all the other members together.

However the ballots are paired, as long as each pair holds two different members, ballots of a member with more than half of them are left over.

The brute force: count every candidate

For each ballot, count how many ballots name the same member, and stop at a member with more than half. With no winner, every ballot is compared with every ballot. Counting all members at once with a hash map is fast, but it breaks the machine’s memory rule:

Counting with scans, and the memory of counting with a map Python · brute/count_each.py
"""The outright winner of a ballot box, by brute force: count every candidate's ballots with a scan."""
import tracemalloc
from collections import Counter


def winner_brute(ballots):
    """Returns (winner or -1, comparisons): for each ballot, count how many ballots name the same member."""
    comparisons = 0
    for candidate in ballots:
        votes = 0
        for ballot in ballots:
            comparisons += 1
            votes += ballot == candidate
        if 2 * votes > len(ballots):
            return candidate, comparisons
    return -1, comparisons


print(winner_brute([4, 7, 4, 4, 2, 4])[0])
print(winner_brute([3, 3, 5, 5])[0])
print(winner_brute([9])[0])

# The slowest case is a box with no winner: every ballot's candidate is counted against every ballot.
for n in (1_000, 2_000):
    print(f"n = {n:,}: {winner_brute(list(range(n)))[1]:,} comparisons")

# Counting every candidate at once is fast, but it needs memory for every member number that appears.
ballots = list(range(1, 200_001))  # 200,000 different members, one ballot each
tracemalloc.start()
counts = Counter(ballots)
peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
print(f"a Counter of {len(counts):,} members: at most {peak // 1024:,} KiB allocated")

Output

4
-1
9
n = 1,000: 1,000,000 comparisons
n = 2,000: 4,000,000 comparisons
a Counter of 200,000 members: at most 15,362 KiB allocated

This output changes from run to run: the memory a Counter takes depends on the size of Python's integers and references, 64-bit or 32-bit

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 count_each.py

The scans make n² comparisons: 10¹⁴ for 10⁷ ballots. The map stores every distinct member; at 200,000 members it already took about 15 MiB in the recorded run, and 10⁷ distinct members would take about fifty times that. Step through the second example, where every scan runs to the end:

Interactive · step by step Counting every ballot's member in [3, 3, 5, 5] Step through the four scans. Each one counts the member a ballot names by reading the whole box; the narration keeps the count of comparisons.
Counting every ballot's member in [3, 3, 5, 5], step 6 of 6. Showing ballot 0: 3, ballot 1: 3, ballot 2: 5, ballot 3: 5, count of 3 (2 of 4: not a winner), count of 3 again (2 of 4: not a winner), count of 5 (2 of 4: not a winner), count of 5 again (2 of 4: not a winner). In focus: count of 3, count of 3 again, count of 5, count of 5 again.ballot 0: 3ballot 1: 3ballot 2: 5ballot 3: 5count of 32 of 4: not a winnercount of 3 again2 of 4: not a winnercount of 52 of 4: not a winnercount of 5 again2 of 4: not a winner

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Four ballots. The box holds 3, 3, 5 and 5. The brute force takes each ballot's member in turn and counts it with a scan of the whole box.
  2. Ballot 0 names 3. The scan compares all four ballots with 3 and finds two. 2 of 4 is not more than half. 4 comparisons so far.
  3. Ballot 1 names 3. The same member is counted again, with another full scan: 2 of 4 once more. 8 comparisons so far.
  4. Ballot 2 names 5. Two ballots name 5: 2 of 4. 12 comparisons so far.
  5. Ballot 3 names 5. A last full scan finds 5 twice again. After 16 comparisons nobody has more than half, so the answer is −1.
  6. Why it is slow. With no winner, every ballot is compared with every ballot: n² comparisons, 16 here and 10¹⁴ for 10⁷ ballots.

What to notice

A majority member has more ballots than all the other members together. Pair each ballot for any other member with one ballot for the majority member: the other ballots run out first, so some ballots for the majority member are always left over, as the figure shows. Three approaches are in common use:

  • Counting with a hash map gives every member’s total in one pass, but needs memory for every distinct member.
  • Sorting the ballots puts a majority member at the middle position, n // 2, in O(n log n) time.
  • The Boyer–Moore vote keeps one candidate and one counter and cancels pairs of different ballots. A second pass counts the survivor, so two passes and O(1) extra memory settle the question.

Checkpoint

Check: An outright winner has more than half · Counting every candidate, and its cost · A majority outnumbers all the others

  1. Question 1 of 3 Which of these ballot boxes has an outright winner?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: [2, 2, 1]

    An outright winner has more than half of the ballots: 2 × votes > n. Exactly half is not enough, as the second example of the problem shows.

  2. Question 2 of 3 How many comparisons does the scan-counting brute force make on a box of 2,000 ballots for 2,000 different members?

    Type a number.

    A hint

    With no winner, every ballot's member is counted with a scan of all the ballots.

    Show the answer: Question 2 of 3

    Answer: 4000000 comparisons

    No member reaches more than half, so all 2,000 scans run to the end: 2,000 × 2,000 = 4,000,000 comparisons, the number the program printed.

  3. Question 3 of 3 In [4, 7, 4, 4, 2, 4], each ballot for another member is paired with a ballot for 4. How many ballots for 4 are left over?

    Type a number.

    Show the answer: Question 3 of 3

    Answer: 2 ballots

    Four ballots name 4 and two name someone else. Pairing the 7 and the 2 with one 4 each leaves 4 − 2 = 2 ballots for 4, as the figure shows.

The practice below starts with whatever you know least.

Practice that adapts to you

Practise this lesson

9 questions about 9 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 9 For [3, 3, 5, 5], why is the answer −1?

    Choose one answer.

    Show the answer: Question 1 of 9

    Answer: Two ballots of four is exactly half, and a winner needs more than half

    More than half is strict: 2 × votes > n. With 2 of 4, neither 3 nor 5 passes it.

  2. Question 2 of 9 What is the answer for [6, 1, 6, 2, 6]?

    Choose one answer.

    Show the answer: Question 2 of 9

    Answer: 6

    A winner needs more than half of the ballots: 3 of 5 is enough, as 4 of 6 is in the first example.

  3. Question 3 of 9 Why can a ballot box have at most one outright winner?

    Choose one answer.

    Show the answer: Question 3 of 9

    Answer: Two members with more than half each would need more ballots than the box holds

    More than half for two members would mean more than n ballots in all, so at most one member can win outright.

  4. Question 4 of 9 Which box makes the scan-counting brute force slowest?

    Choose one answer.

    Show the answer: Question 4 of 9

    Answer: A box with no winner, where every ballot's scan runs to the end

    The slowest case is a box with no winner: n scans of n ballots, n² comparisons.

  5. Question 5 of 9 About how many comparisons does the brute force make on 10⁷ ballots with no winner?

    Choose one answer.

    Show the answer: Question 5 of 9

    Answer: 10¹⁴

    n² comparisons for n = 10⁷ is 10¹⁴, far beyond any time limit.

  6. Question 6 of 9 A Counter of 200,000 different members took about 15 MiB in the recorded run. Why does it not solve the problem as stated?

    Choose one answer.

    Show the answer: Question 6 of 9

    Answer: The machine can store only a handful of numbers, and a map stores one entry per distinct member, up to 10⁷

    Ten million distinct members would need about fifty times the 15 MiB of the recorded run, where the machine has room for a handful of numbers.

  7. Question 7 of 9 Which of the three ways in common use fits the counting machine's memory rule?

    Choose one answer.

    Show the answer: Question 7 of 9

    Answer: The Boyer–Moore vote

    The vote reads the ballots twice and keeps a handful of numbers, which is exactly what the machine allows.

  8. Question 8 of 9 After sorting [4, 7, 4, 4, 2, 4], which position must hold the majority member, if there is one?

    Choose one answer.

    Show the answer: Question 8 of 9

    Answer: Position n // 2 = 3, the middle

    The sorted box is [2, 4, 4, 4, 4, 7], and position 3 holds 4. The middle element is still only a candidate when no majority is promised.

  9. Question 9 of 9 A box may have no winner at all. Why does the vote need a second pass over the ballots?

    Choose one answer.

    Show the answer: Question 9 of 9

    Answer: The first pass always leaves some candidate, even in a box with no winner, so its ballots must be counted

    With a majority the survivor is the winner; without one a survivor still comes out, so only a count says which case the box is in.

The vote, step by step Pro: opens with a Pro, Premium or Ultimate pass

In this part:

  • Why a majority survives: the invariant and the proof
  • The vote and its check in 14 languages
  • Counting against voting, measured
  • More than a third: two candidates, two counters
  • Variants, edge cases and the common bugs
    • Variants
    • Edge cases and common bugs
  • Practice: every member with more than a third
    • Every member with more than a third of the votes
  • Interview questions
    • A poll's votes are stored on 8 machines, about 10⁸ on each. Find the member with more than half of all the votes, if there is one, moving as little data as possible between machines. What does each machine compute, what does it send, and how do you confirm the answer?
    • A stream of 10⁹ votes can be read only once, and you may keep only a few numbers. At the end you must report the majority member if there is one. What can you guarantee, and what is impossible?
    • Find every URL that appears on more than 1 % of 10⁹ log lines, with 1 MB of memory and two passes over the log. How many candidates do you keep, what does each pass do, and what can you report if only one pass is allowed?
  • Key takeaways

3 diagrams · 4 runnable examples (Python) · 1 exercise with sample tests · 3 interview answers · about 39 minutes

Opening this part with your pass…

This part opens with any MySmartCoPilot pass.

  • Pro pass · 1 week₹79$2.99
  • 30 days₹179$5.99
  • 1 year₹1,699$45

One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.

It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).

Terms in this lesson

heavy hitter
A value whose count passes a fixed share of all the items of a stream, such as more than 1 % of them. Finding heavy hitters with little memory is a classic problem of stream processing.
majority element
A value that fills more than half of a list, such as 4 in [4, 7, 4, 4, 2, 4]. A list has at most one, and exactly half is not enough.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.