EasyNo. 0169

Majority Element — LeetCode 169 Python Solution

Pattern
Sorting
Topics
Array, Hash Table, Divide and Conquer, Counting, Sorting
On study lists
Grind 75 and Top Interview 150
Reading time
2 min

The problem

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

Example

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

Python solution

PythonSolution
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        cnt = m = 0
        for x in nums:
            if cnt == 0:
                m, cnt = x, 1
            else:
                cnt += 1 if m == x else -1
        return m

Complexity

Time
O(n)where n is the length of the array nums
Space · auxiliary
O(1)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 169. Majority Element 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

Related problems
No.ProblemDifficulty
0229Majority Element IIMedium
0347Top K Frequent ElementsMedium
0594Longest Harmonious SubsequenceEasy
0621Task SchedulerMedium
0692Top K Frequent WordsMedium
09233Sum With MultiplicityMedium

Frequently asked questions

How hard is LeetCode 169. Majority Element?

LeetCode 169. Majority Element is rated Easy on LeetCode.

What is the time complexity of LeetCode 169. Majority Element?

The Python solution on this page runs in O(n), where n is the length of the array nums.

What is the space complexity of LeetCode 169. Majority Element?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 169. Majority Element cover?

LeetCode 169. Majority Element is tagged Array, Hash Table, Divide and Conquer, 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.

Free to download. Check it runs on your machine, then pick a plan.