One value fills more than half the list. Boyer–Moore voting pairs off different values like rival fighters knocking each other off a hill, and the majority is the one left standing, in one pass and O(1) space.
▼The problem
LeetCode 169 (Easy). Given an array nums of size n, return the majority element: the value that appears more than n / 2 times. It is guaranteed to exist.
Examples (LeetCode's): [3,2,3] → 3 (scene 1); [2,2,1,1,1,2,2] → 2 (the example and walkthrough: 2 appears 4 times, more than 3.5).
The solution
def majorityElement(nums):
count = 0
for x in nums:
if count == 0:
cand = x
count += 1 if x == cand else -1
return candTranscript
Majority Element. One value in a list of numbers appears more than half the time. Find it. That value always exists: in three, two, three, three appears twice, so the answer is three.
Our example: two, two, one, one, one, two, two. Seven numbers, so half is three and a half. Two appears four times, one appears three. Four is more than half, so the answer is two.
The slow way counts every number against all the others: order n squared, forty-nine checks for seven numbers. A hash map of counts takes linear time, but linear extra memory. Sorting puts the majority in the middle, but it costs n log n.
Boyer-Moore voting needs one pass and almost no memory. Think king of the hill. Keep a candidate, whose flag flies on top, and a count, the height of its tower. A matching number climbs on: plus one. A different number knocks one off, and both leave: minus one. When the hill is empty, the next number plants its own flag.
Let's play the example. Two plants its flag: count one. Another two climbs on: two. A one knocks a two off: one. Another one: zero, the hill is empty. The next one plants its flag: one. A two knocks it off: zero again. The last two takes the hill: the answer is two.
Why does this work? Each knockout removes two different numbers, and at most one of them is the majority. Here, three knockouts each took one two. The majority has more than half the votes, so it can never be cancelled completely. It's the one left standing.
In code, start the count at zero and loop over the numbers. When the count is zero, the current number becomes the candidate. Then add one on a match, or subtract one. Return the candidate.
Each number is visited once, so the time is order n. We only keep a candidate and a count, so the space is order one.
Pair off, cancel out, and the majority is left standing. That's Majority Element.