Who has more than half the votes
Find the value that fills more than half the list by finding each half's winner and counting both. About 14 minutes.
A winner must win a half
Votes are cast in a row, and a candidate wins only with more than half the votes. Split the row into a left half and a right half. If someone has more than half of everything, they can't be at or below half in both halves. So they must have more than half in at least one of them.
That gives two candidates at most: the winner of the left half and the winner of the right half. Find them recursively, then count each one over the whole range.
def count(lo, hi):
if lo == hi:
return 1 if nums[lo] == x else 0
mid = (lo + hi) // 2
a = count(lo, mid)
b = count(mid + 1, hi)
return a + bSplit into 3, 3, 3, 1 and 2, 3, 1. A winner of the whole list must win one of these halves.
Count to confirm
A half's winner might still lose over the whole range, so count. If both halves agree, that value wins the whole range, because it has more than half in each half. If they disagree, count each candidate over the whole range and keep the one with more than half.
If neither has more than half, nobody wins: return -1. A range with no winner reports -1, and that is a valid answer for the merge.
total = 0
for v in nums[lo:hi + 1]:
if v == cand:
total += 1
size = hi - lo + 1
confirmed = total > size // 2Both halves have winner 5. Do you need to count anything over the whole range?
- ANo: 5 has more than half in each half, so more than half overall
- BYes, always count over the whole range
- COnly if the halves have different sizes
Show the answer
No: 5 has more than half in each half, so more than half overall. Two parts each above half add up to above half of the whole.
Majority by halves
nums is a list of non-negative whole numbers. A majority value appears more than half the length times. Return the majority value, or -1 if there isn't one. Use a recursive function that splits the list in half.
nums = [2, 2, 1, 1, 1, 2, 2] → 2
0 ≤ length ≤ 100,000 · 0 ≤ value ≤ 1,000,000,000