Algo-Sim › Arrays & Hashing

Majority Element

Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Boyer–Moore voting: keep one candidate and a count; differing values cancel in pairs and the majority survives.

Problem

An array nums of length n contains one value that occurs more than n / 2 times. Return that value. Can you do it in linear time with only O(1) extra space?

Constraints

Edge cases to test

Follow-up questions

What if a majority might not exist?
Run Boyer–Moore, then do a second pass to count the candidate and check it really appears more than n / 2 times: still O(n), O(1).
What about every value appearing more than n / 3 times?
Keep two candidates and two counts (LC 229); at most two values can qualify. Verify with a second pass: O(n) time, O(1) space.

Solution

Java

public int majorityElement(int[] nums) {
    int candidate = 0, count = 0;
    for (int x : nums) {
        if (count == 0) candidate = x;
        count += (x == candidate) ? 1 : -1;
    }
    return candidate;
}

Python

def majority_element(nums):
    candidate, count = 0, 0
    for x in nums:
        if count == 0: candidate = x
        count += 1 if x == candidate else -1
    return candidate

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int majorityElement(vector<int> &nums) {
        int candidate = 0, count = 0;
        for (int x : nums) {
            if (count == 0) candidate = x;
            count += (x == candidate) ? 1 : -1;
        }
        return candidate;
    }
};

More Arrays & Hashing problems