Majority Element II — LeetCode 229 Python Solution

MediumArrayHash TableCountingSorting
Problem
#229
Pattern
Sorting
Reading time
3 min

The problem

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Example

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

Python solution

Python
class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        n1 = n2 = 0
        m1, m2 = 0, 1
        for m in nums:
            if m == m1:
                n1 += 1
            elif m == m2:
                n2 += 1
            elif n1 == 0:
                m1, n1 = m, 1
            elif n2 == 0:
                m2, n2 = m, 1
            else:
                n1, n2 = n1 - 1, n2 - 1
        return [m for m in [m1, m2] if nums.count(m) > len(nums) // 3]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 229. Majority Element II is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 229. Majority Element II?
LeetCode 229. Majority Element II is rated Medium on LeetCode.
What is the time complexity of LeetCode 229. Majority Element II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 229. Majority Element II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 229. Majority Element II cover?
LeetCode 229. Majority Element II is tagged Array, Hash Table, Counting and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview