Example 1
- Input
- nums = [3, 2, 3]
- Output
- 3
3 appears twice, which is more than 3 / 2 = 1.5, so 3 is the majority element.
Given an array of size n where one element appears more than n divided by 2 times, return that majority element. The input guarantees such an element always exists.
Given an integer array nums of length n, return the value that occurs strictly more than half the time. Such a majority element is guaranteed to exist.
A majority needs at least floor(n / 2) + 1 occurrences; being the most frequent value alone is insufficient.
Follow-up: find it in time with extra space.
n == nums.length1 <= n <= 5 * 10^4-10^9 <= nums[i] <= 10^93 appears twice, which is more than 3 / 2 = 1.5, so 3 is the majority element.
2 appears four times, which is more than 7 / 2 = 3.5, so 2 is the majority element.
The only value occurs once, more than 1 / 2. A negative majority is a valid answer, so -1 must not be treated as a missing-answer marker.
Imagine removing two different values together until no such pair remains. Each pair consumes at most one occurrence of the majority, and there are fewer other values than majority occurrences, so some majority occurrences must survive. In [3, 2, 3], cancelling the first 3 with 2 leaves 3. Boyer-Moore voting simulates these removals with a candidate value and a count of its unmatched occurrences; that count is not the candidate's total frequency.
Reveal Brute Force: intuition, complexity, and code
5 * 10^4 elements.[-1] returns -1; zero and negative candidates are ordinary values, not special markers.[7, 7, 7, 7] returns 7, and the voting count increases on every element.[1, 2, 2, 2] returns 2; two copies would only tie half the length.[1, 2, 3, 3, 3] cancels 1 with 2, then adopts the later majority 3.[-1000000000, 1000000000, -1000000000] returns -1000000000; the algorithm compares values without subtracting them.[1, 2, 3] leaves a candidate but has no majority. That variant requires a frequency verification pass; empty arrays are outside this problem's constraints.count >= floor(n / 2) in brute force admits a tie; use a strict greater-than comparison.1 although the majority 3 occurs twice.When one value is guaranteed to outnumber all others combined, pairwise cancellation finds it in linear time with constant space.