SMALLTALK LAB
Boyer-Moore majority vote: cancel pairs, then verify
Find a strict majority in linear time with one candidate and one balance. Build a two-pass Smalltalk solution, explain its cancellation invariant, and test false survivors, ties, nil and empty input.
Before you begin
Use native Squeak 6.1 and a Workspace. Select one complete checkpoint and choose Print it. Every checkpoint defines its own inputs and can run independently; no classes or packages are installed. Literal words inside #( ... ) are Symbols. The data must be finite, repeatable and unchanged across both passes, with stable value equality. Use Do it for the separate Morphic board and change its stage from 0 through 4.
These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.
01 - Define a strict majority before choosing a candidate
A strict majority occupies more than half the positions. It is stronger than being the most frequent value: a plurality can win a frequency ranking without crossing halfway. Multiplying the count by two avoids rounding and keeps the boundary exact for odd and even lengths.
| values count |
values := #(amber blue amber amber coral amber amber).
count := values count: [:item | item = #amber].
{values size. count. count * 2 > values size.
2 * 2 > 4. 3 * 2 > 5}Expected: #(7 5 true false true)

Try it: Replace the input with #(amber blue amber blue). Amber occurs exactly half the time, so its majority test must be false.
02 - Cancel unequal values with one balance
Keep a candidate and a balance of unmatched copies. Matching values increase the balance; a different value cancels one copy. When the balance is zero, the next value starts a new group. The final balance is not the candidate’s total frequency: this scan leaves three unmatched amber copies, although amber appeared five times.
| values candidate balance |
values := #(amber blue amber amber coral amber amber).
candidate := nil. balance := 0.
values do: [:item |
balance = 0
ifTrue: [candidate := item. balance := 1]
ifFalse: [item = candidate
ifTrue: [balance := balance + 1]
ifFalse: [balance := balance - 1]]].
{candidate. balance}Expected: #(amber 3)

Try it: Walk through the first two items: amber gives balance 1 and blue reduces it to 0. The next item replaces the exhausted candidate.
03 - Trace the cancellation invariant
Each row records the current item, candidate and balance after processing it. At every prefix, the processed items can be partitioned into pairs of unequal values plus balance copies of candidate. A zero balance means the residue is empty; the stored candidate may still contain a stale value and carries no evidence by itself.
| values candidate balance trace |
values := #(amber blue amber amber coral amber amber).
candidate := nil. balance := 0.
trace := OrderedCollection new.
values do: [:item |
balance = 0
ifTrue: [candidate := item. balance := 1]
ifFalse: [item = candidate
ifTrue: [balance := balance + 1]
ifFalse: [balance := balance - 1]].
trace add: {item. candidate. balance}].
trace asArrayExpected: #(#(amber amber 1) #(blue amber 0) #(amber amber 1) #(amber amber 2) #(coral amber 1) #(amber amber 2) #(amber amber 3))

Try it: After the fifth item, identify two unequal pairs and the single leftover amber. A trace is useful for learning, but storing it changes the extra-space cost to O(n).
04 - Verify the survivor in a second pass
If a strict majority exists, canceling unequal pairs cannot eliminate it: each removed pair takes away at most one majority item and one other item, so the majority’s excess survives. This proves that any true majority must be the final candidate. It does not prove that the candidate is a majority. Count it in the original input to settle that question.
| values candidate balance occurrences |
values := #(amber blue amber amber coral amber amber).
candidate := nil. balance := 0.
values do: [:item |
balance = 0
ifTrue: [candidate := item. balance := 1]
ifFalse: [item = candidate
ifTrue: [balance := balance + 1]
ifFalse: [balance := balance - 1]]].
occurrences := values count: [:item | item = candidate].
{candidate. balance. occurrences.
occurrences * 2 > values size}Expected: #(amber 3 5 true)

Try it: Try #(amber blue coral). The survivor is coral with balance 1, but only one of three original positions contains coral.
05 - Expose a positive balance with no majority
This fixture ends with a positive balance, yet the survivor occurs only twice in five positions. Boyer-Moore is a candidate generator, not a most-frequent-value counter. Different input orderings can even leave different candidates when no majority exists; verification must still reject them.
| values candidate balance occurrences |
values := #(amber blue coral amber coral).
candidate := nil. balance := 0.
values do: [:item |
balance = 0
ifTrue: [candidate := item. balance := 1]
ifFalse: [item = candidate
ifTrue: [balance := balance + 1]
ifFalse: [balance := balance - 1]]].
occurrences := values count: [:item | item = candidate].
{candidate. balance. occurrences.
occurrences * 2 > values size}Expected: #(coral 1 2 false)

Try it: Try #(amber amber blue blue coral). It also has no strict majority. Do not replace the verification test with balance > 0.
06 - Make absence explicit, including an empty input
The reusable block returns #(found candidate occurrences). When found is false the candidate field is only diagnostic, not a result to use. This separate Boolean also allows nil itself to be a legitimate majority value. Empty input has zero matches and fails the strict inequality, while a singleton always passes.
| majority |
majority := [:items | | choice votes occurrences |
choice := nil. votes := 0.
items do: [:each |
votes = 0
ifTrue: [choice := each. votes := 1]
ifFalse: [each = choice
ifTrue: [votes := votes + 1]
ifFalse: [votes := votes - 1]]].
occurrences := items count: [:each | each = choice].
{occurrences * 2 > items size. choice. occurrences}].
{majority value: #().
majority value: #(amber).
majority value: #(amber blue).
majority value: #(nil nil amber).
majority value: #(amber blue amber)}Expected: #(#(false nil 0) #(true amber 1) #(false amber 1) #(true nil 2) #(true amber 2))

Try it: A nil-only return convention would confuse an absent majority with a genuine nil majority. Read the first field before interpreting the second.
07 - Use value equality rather than object identity
Votes normally represent values, so the scan and recount both use =. Two separately created strings with the same text are equal votes even though they are different objects. Identity comparison with == would split them. Choose the same stable equality relation in both passes and avoid changing values between passes.
| values candidate balance occurrences firstText secondText |
firstText := 'amber' copy. secondText := 'amber' copy.
values := {firstText. 'blue'. secondText}.
candidate := nil. balance := 0.
values do: [:item |
balance = 0
ifTrue: [candidate := item. balance := 1]
ifFalse: [item = candidate
ifTrue: [balance := balance + 1]
ifFalse: [balance := balance - 1]]].
occurrences := values count: [:item | item = candidate].
{firstText = secondText. firstText == secondText.
occurrences. occurrences * 2 > values size}Expected: #(true false 2 true)

Try it: The returned candidate can be either equal string instance. The algorithm promises an equal value, not the first object identity or its original index.
08 - Check results against a frequency-table oracle
A Dictionary gives an independent, memory-heavier answer: count every distinct value and select all entries above half. At most one value can qualify. The small regression suite covers empty input, a singleton, an exact tie, a genuine majority, a false survivor, nil and a late candidate change. The final result is true only when every Boolean and every accepted value agrees.
| majority cases |
majority := [:items | | choice votes occurrences |
choice := nil. votes := 0.
items do: [:each |
votes = 0
ifTrue: [choice := each. votes := 1]
ifFalse: [each = choice
ifTrue: [votes := votes + 1]
ifFalse: [votes := votes - 1]]].
occurrences := items count: [:each | each = choice].
{occurrences * 2 > items size. choice. occurrences}].
cases := #(#() #(amber) #(amber blue)
#(amber blue amber) #(amber blue coral amber coral)
#(nil nil amber) #(blue coral amber amber amber)).
cases allSatisfy: [:sample | | result counts winners |
result := majority value: sample.
counts := Dictionary new.
sample do: [:entry |
counts at: entry put: (counts at: entry ifAbsent: [0]) + 1].
winners := counts keys select: [:key |
(counts at: key) * 2 > sample size].
(result first = winners notEmpty) and: [
result first not or: [winners includes: result second]]]Expected: true

Try it: Add adversarial orders and longer runs. For general keys, the Dictionary oracle also requires equal objects to have equal hash values; the two-pass scan itself does not require hashing.
Watch the computed states

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.
Reason about correctness and limits
A candidate is not a verified answer. Positive balance does not prove a majority, and balance is not an occurrence count. Recount the candidate in the original collection unless a majority is guaranteed by a trusted input contract.
The threshold is strictly more than n/2. Use occurrences * 2 > items size, not >=. A two-way tie is not a majority; a unique most frequent value need not be a majority either.
The invariant is a decomposition of each prefix into unequal pairs and balance identical leftovers. Removing an unequal pair cannot destroy an existing strict majority, because it removes at most one copy of that value. This explains why a true majority survives cancellation, not why every survivor is a true majority.
Two passes take O(n) time and O(1) auxiliary storage, assuming constant-cost equality and traversal. The input collection is not auxiliary storage. The tutorial trace, Morphic history and Dictionary oracle deliberately use additional memory. Large-object comparisons can cost more than O(1).
The verification pass needs the original sequence again. A one-way stream must be replayable or stored elsewhere, unless the existence of a majority is guaranteed. This implementation uses collections, not a promise of exact one-pass verification for an arbitrary stream.
Keep equality consistent and inputs unchanged during both passes. This algorithm finds one strict majority, not a mode, all frequent values, weighted votes or all values above n/3. Those tasks need different counting or cancellation rules.
Three practice challenges
Construct a convincing false survivor
Predict candidate, balance, occurrence count and verification for #(red red blue green green). Then check by changing checkpoint 5.
Show solution
The state sequence is red/1, red/2, red/1, red/0, green/1. The final tuple is #(green 1 2 false). A late survivor with positive balance can still fail the strict majority threshold.
Prove that two majorities cannot coexist
Why can the Dictionary oracle find at most one winner? Does this remain true if the threshold changes to at least half?
Show solution
Two different values each occurring more than n/2 times would require more than n total positions, which is impossible. With at least half, an even-sized tie can produce two winners, for example #(red red blue blue). That weaker condition is not the contract used here.
Generate an adversarial late majority
Arrange three blue and four amber votes so the final candidate changes late. Predict the accepted value and explain why the ordering cannot change it.
Show solution
Use #(blue blue blue amber amber amber amber). After six items balance is zero; the seventh installs amber with balance one. Recounting finds four amber occurrences out of seven and accepts it. The invariant guarantees the same accepted value for any permutation, although balances and intermediate candidates can differ.
Continue learning
Collections | Reservoir Sampling | Online Variance | Testing
Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.