Problem overview
The method majorityElement gets an int[] named nums in which one value makes up more than half of the array. It returns that value. Every input has such a value, so there is always exactly one answer.
In [5,9,5,5,1] the value 5 appears 3 times out of 5, which is more than half, so the answer is 5. In [0,4,4,0,4,0,4,0,4] the 4 appears 5 times out of 9 and the 0 only 4 times, so the answer is 4. In [-8,2,-8,-8] the answer is -8, with 3 out of 4. Exactly half would not be enough: more than half of 4 means at least 3.
Approach: the majority of a range wins one of its halves
The statement asks for O(n log n) time, which points to divide and conquer, the idea behind merge sort. Cut the range into a left half and a right half and solve each half the same way, down to single numbers.
The key fact: if a value fills more than half of a range, it fills more than half of at least one of the two halves. If it were at most half of both, it would be at most half of the whole range. So the majority of the range is the majority of the left half, the majority of the right half, or both. After the two recursive calls you have at most two candidates:
- If both halves return the same value, that value is the answer for the range.
- If they return different values, count both across the whole range and keep the one that appears more.
When the range really has a majority, it beats the other candidate in that count. A half that has no majority returns some value that means nothing for that half, but this is harmless: if the whole range has a majority, it is the majority of the other half, so it is the other candidate, and the count picks it.
Other solutions exist: a hash map of counts runs in O(n) time with O(n) space, sorting puts the answer in the middle position, and Boyer-Moore voting needs O(1) space. This lesson practises recursion, so it uses halving.
Step by step
- Start the recursion.
majorityElementreturns what the helpermajorityfinds for the whole array, from index 0 tonums.length - 1. - Write the helper's signature. It takes the array and the inclusive bounds
leftandrightof the range it looks at, and returns anint. - Base case. A range of one number: that number is the majority of its range. This case also ends the recursion.
- Find the middle. The left half is
lefttomiddleand the right half ismiddle + 1toright. Integer division drops the remainder, so both halves are never empty when the range has two or more numbers. - Solve the left half and keep the result as
leftMajority. - Solve the right half and keep the result as
rightMajority. - Agreement. If the two are equal, return that value.
- Disagreement. Only these two values can be the range's majority. Start two counters at 0.
- Count over the range with a loop from
lefttoright, both included. - Count the left candidate with an
ifinside the loop. - Count the right candidate with a second
if. The two values differ, so at most one of the two counters grows for each number. - Keep the winner. If
leftCountis greater, returnleftMajority. - Otherwise return
rightMajority. A tie means neither value is a majority of this range, so either may be returned.
The solution in Java
class Solution {
int majority(int[] nums, int left, int right) {
if (left == right) {
return nums[left];
}
int middle = (left + right) / 2;
int leftMajority = majority(nums, left, middle);
int rightMajority = majority(nums, middle + 1, right);
if (leftMajority == rightMajority) {
return leftMajority;
}
int leftCount = 0;
int rightCount = 0;
for (int i = left; i <= right; i++) {
if (nums[i] == leftMajority) {
leftCount++;
}
if (nums[i] == rightMajority) {
rightCount++;
}
}
if (leftCount > rightCount) {
return leftMajority;
}
return rightMajority;
}
public int majorityElement(int[] nums) {
return majority(nums, 0, nums.length - 1);
}
}
Java details worth a look:
- Comparing with
==is right here because the values are primitiveints. With a list ofIntegerobjects,==would compare references, and you would needequals. - Inclusive bounds.
rightis the last index, not one past it, so the loop usesi <= rightand the first call passesnums.length - 1. - The middle.
(left + right) / 2is fine for array indexes in this lesson. For indexes near theintlimit, the sum would wrap silently:(Integer.MAX_VALUE + Integer.MAX_VALUE) / 2gives -1.left + (right - left) / 2avoids that. - Helper first or last. Java doesn't care about the order of methods in a class, so
majoritycan sit above or belowmajorityElement.
Complexity
On each level of the recursion, the ranges together cover the array once, so the counting loops do at most n comparisons per level in total. Halving gives about log n levels, so the time is O(n log n). The calls go about log n deep, so the extra space is O(log n). The array itself is never copied or changed.
Edge cases and common mistakes
- One number.
[7]returns 7 at once from the base case. - Odd lengths.
[3,3,4]splits into[3,3]and[4]and returns 3. The halves can have different sizes; the argument about halves still holds. - Counting only inside a half. When the halves disagree, the counts must run over the whole range. Counting each candidate only in its own half would make both counts look big.
- Trusting a half's answer when it has no majority. A half may return a value that isn't its majority. The count in the combine step is what makes the final answer correct.
- Off-by-one in the halves. Using
middlefor both halves would never shrink a two-number range and the recursion would not end. - Negative numbers are ordinary values here.
[-8,2,-8,-8]returns -8.
Testing
| nums | Result |
|---|---|
[5,9,5,5,1] | 5 |
[0,4,4,0,4,0,4,0,4] | 4 |
[-8,2,-8,-8] | -8 |
[7] | 7 |
[3,3,4] | 3 |
[1,2,1,2,1] | 1 |
