Majority Element

Easyarrayhash-tabledivide-and-conquer
Category: Array & Hashing
Companies that ask this question:
AmazonGoogleAdobeApple

Approach

Majority Element

Problem Statement

Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times.

You may assume that the majority element always exists in the array.

Examples

Example 1:

Input: nums = [3,2,3]
Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2

Approach

Boyer-Moore Voting Algorithm: Maintain a candidate and count. If count = 0, change candidate. If element matches candidate, increment count; else decrement.

Complexity

  • Time: O(n)
  • Space: O(1)

Solution

java
1class Solution {
2    public int majorityElement(int[] nums) {
3        int candidate = nums[0];
4        int count = 0;
5        
6        for (int num : nums) {
7            if (count == 0) candidate = num;
8            count += (num == candidate) ? 1 : -1;
9        }
10        
11        return candidate;
12    }
13}
Loading visualizer...