Start learning free

LESSON 115 OF 321 · DIVIDE AND CONQUER

Majority Element in Java: Divide and Conquer in O(n log n)

Practice O(n log n) Read the full explanation

You get an array nums. One value makes up more than half of it. Return that value.

For example, in an array of 7 numbers, that value appears at least 4 times. Every input has such a value.

 

Example 1:

Input: nums = [5,9,5,5,1]
Output: 5
Explanation: There are 5 numbers, and 5 appears 3 times.
3 is more than half of 5.

Example 2:

Input: nums = [0,4,4,0,4,0,4,0,4]
Output: 4
Explanation: 4 appears 5 times out of 9.
0 appears 4 times, which is not more than half.

Example 3:

Input: nums = [-8,2,-8,-8]
Output: -8
Explanation: -8 appears 3 times out of 4.
Exactly half, 2 times, would not be enough.

 

Constraints:

  • 1 to 100,000 numbers.
  • Each number is a whole number from −1,000,000,000 to 1,000,000,000.
  • One value always makes up more than half of nums.

Note:

Your solution should run in O(n log n) time.

Boyer-Moore voting is a known trick that solves it in O(n) time and O(1) space.



Cut nums into a left half and a right half. The value you want makes up more than half of at least one of the two halves.

Find the majority of each half the same way, down to single numbers. If both halves give the same value, that is the answer. If not, count both values in the whole range and keep the one that appears more.

Each level of halving counts at most n numbers, and there are about log n levels: O(n log n) time.
The recursion is about log n calls deep, so the extra space is O(log n).
STEP 1 OF 13
    Ctrl + Enter to check

    JAVA · DIVIDE AND CONQUER

    Majority Element in Java, explained

    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

    1. Start the recursion. majorityElement returns what the helper majority finds for the whole array, from index 0 to nums.length - 1.
    2. Write the helper's signature. It takes the array and the inclusive bounds left and right of the range it looks at, and returns an int.
    3. Base case. A range of one number: that number is the majority of its range. This case also ends the recursion.
    4. Find the middle. The left half is left to middle and the right half is middle + 1 to right. Integer division drops the remainder, so both halves are never empty when the range has two or more numbers.
    5. Solve the left half and keep the result as leftMajority.
    6. Solve the right half and keep the result as rightMajority.
    7. Agreement. If the two are equal, return that value.
    8. Disagreement. Only these two values can be the range's majority. Start two counters at 0.
    9. Count over the range with a loop from left to right, both included.
    10. Count the left candidate with an if inside the loop.
    11. Count the right candidate with a second if. The two values differ, so at most one of the two counters grows for each number.
    12. Keep the winner. If leftCount is greater, return leftMajority.
    13. 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 primitive ints. With a list of Integer objects, == would compare references, and you would need equals.
    • Inclusive bounds. right is the last index, not one past it, so the loop uses i <= right and the first call passes nums.length - 1.
    • The middle. (left + right) / 2 is fine for array indexes in this lesson. For indexes near the int limit, the sum would wrap silently: (Integer.MAX_VALUE + Integer.MAX_VALUE) / 2 gives -1. left + (right - left) / 2 avoids that.
    • Helper first or last. Java doesn't care about the order of methods in a class, so majority can sit above or below majorityElement.

    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 middle for 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

    numsResult
    [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
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free