File: majority-element/solution.py

Date: 2026-06-06

Time: 17:29

Purpose

This file solves LeetCode 169 — Majority Element. It implements the Boyer-Moore Voting Algorithm to find the element that appears more than n/2 times in an array, and includes inline unit tests. Like every other problem directory in this repo, it's a self-contained solution + test pair.

Key Components

majority_element(nums: list[int]) -> int

The sole function. Takes a non-empty list guaranteed to contain one element with a strict majority (> n/2 occurrences) and returns that element.

The algorithm uses two variables:

Test Suite

Nine tests covering: basic LeetCode examples, single-element and uniform arrays, majority at different positions, negative numbers, and a dominant-majority case. No edge case for empty input, consistent with the problem's guarantee that nums is non-empty with a valid majority.

Patterns

Boyer-Moore Voting Algorithm — This is the canonical O(n) time, O(1) space solution. The key insight: if you pair each occurrence of the majority element with a different element, at least one occurrence of the majority is left unpaired. The counter tracks this surplus.

The algorithm works in a single pass with no data structures — no hash maps, no sorting. This is the optimal approach for this problem.

Inline tests — The unittest import and test class live in the same file as the solution, a pattern used across this repo. The if _name == "main_" guard means tests run via python solution.py directly.

Dependencies

Imports: Only unittest from the standard library. No external dependencies.

Imported by: The "imported by" list in the prompt is misleading — those 400+ testsolution.py files aren't actually importing *this* file. They each import unittest independently. The majority-element/testsolution.py file likely imports majority_element from this module.

Flow

1. Initialize candidate = 0, count = 0

2. For each num in nums:

3. Return candidate

The algorithm never validates that the candidate actually has a majority — it relies on the precondition that one exists. If no majority element exists, the return value is undefined.

Invariants

Error Handling

None. Empty input would return 0 (the initial value of candidate) silently. Invalid input (no majority exists) returns an arbitrary element. This is fine for a LeetCode solution where constraints are guaranteed.

Topics to Explore

Beliefs