Logo
Overview
LeetCode #169 - Majority Element

LeetCode #169 - Majority Element

Jane Doe Jane Doe
August 1, 2025 3 min read
index

πŸ“ Introduction

Given an array nums of size n, return the majority element β€” the element that appears more than ⌊n / 2βŒ‹ times.

*Constraints typically include:

  • It is guaranteed that the majority element always exists in the array.*

πŸ’‘ Approach & Key Insights

*The problem centers on identifying an element that occurs more than n/2 times. Three approaches are commonly used:

  • Brute-force with nested loops.
  • Better approach using hash map frequency counting.
  • Optimal approach using Moore’s Voting Algorithm for O(n) time and O(1) space.*

πŸ› οΈ Breakdown of Approaches

1️⃣ Brute Force / Naive Approach

  • Explanation: For each element, count its frequency using a nested loop. If any element occurs more than ⌊n/2βŒ‹ times, return it.
  • Time Complexity:Β O(nΒ²) – due to nested iterations.
  • Space Complexity:Β O(1)
  • Example/Dry Run:
Input: [3, 2, 3]
Step 1: Check 3 β†’ appears 2 times β†’ not > 1.5
Step 2: Check 2 β†’ appears 1 time β†’ not > 1.5
Return 3

2️⃣ Better Approach

  • Explanation: Use a hash map to store frequencies of each number. As you update counts, if any value exceeds ⌊n/2βŒ‹, return it.
  • Time Complexity:Β O(n) – single pass to count.
  • Space Complexity:Β O(n) – for storing frequencies.
  • Example/Dry Run:
Input: [2, 2, 1, 1, 1, 2, 2]
Count Map:
{2: 1}
{2: 2}
{2: 2, 1: 1}
...
{2: 4, 1: 3}
Check: 4 > floor(7/2) = 3 β†’ return 2

3️⃣ Optimal Approach

  • Explanation: Use Moore’s Voting Algorithm. Keep a count and a candidate. If count is zero, pick a new candidate. If current number equals candidate, increment count. Else decrement. At the end, the candidate is the majority element.
  • Time Complexity:Β O(n) – single pass.
  • Space Complexity:Β O(1) – constant space.
  • Example/Dry Run:
Input: [2, 2, 1, 1, 1, 2, 2]
Step-by-step:
candidate = 2, count = 1
2 == 2 β†’ count = 2
1 != 2 β†’ count = 1
1 != 2 β†’ count = 0 β†’ candidate = 1, count = 1
1 == 1 β†’ count = 2
2 != 1 β†’ count = 1
2 != 1 β†’ count = 0 β†’ candidate = 2, count = 1
Final candidate = 2 β†’ return 2

πŸ“Š Complexity Analysis

ApproachTime ComplexitySpace Complexity
Brute ForceO(nΒ²)O(1)
Hash Map CountingO(n)O(n)
Moore’s Voting AlgoO(n)O(1)

πŸ“‰ Optimization Ideas

The Moore’s Voting Algorithm is already optimal, with a single pass and constant space. If the array does not guarantee a majority element, a second pass is needed to verify the candidate.


πŸ“Œ Example Walkthroughs & Dry Runs

Example: [3, 3, 4, 2, 4, 4, 2, 4, 4]
Step-by-step:
candidate = 3, count = 1
3 == 3 β†’ count = 2
4 != 3 β†’ count = 1
2 != 3 β†’ count = 0 β†’ candidate = 2
...
Final candidate = 4 β†’ verify by count = 5
n = 9 β†’ ⌊9/2βŒ‹ = 4 β†’ 5 > 4 β†’ return 4

πŸ”— Additional Resources


Author: Neha Amin

Date: 19/07/2025

Related Posts