DevPath

← All problems

Majority Element

Easy arrays

Description

Return the element that appears more than n/2 times. A majority element always exists.

Constraints

1 <= n <= 100000

Examples

Input: nums = [3,2,3]

Output: 3

Hints (1)
  • The Boyer-Moore voting algorithm keeps a candidate and a balance.

Solutions

Boyer-Moore voting. · Time O(n) · Space O(1)

func majorityElement(nums []int) int {
    candidate, count := 0, 0
    for _, n := range nums {
        if count == 0 {
            candidate = n
        }
        if n == candidate {
            count++
        } else {
            count--
        }
    }
    return candidate
}

Create a free account to submit solutions, track progress and save problems.

Create account