Problem 169

Abstract / Summary

Find the number that appears more than half the time in a list of integers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0169.cpp

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        auto mid = nums.size() / 2;
        nth_element(nums.begin(), nums.begin() + mid, nums.end());
        return nums[mid];
    }
};
8 lines | 216 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (8+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Counting
  • Divide And Conquer
  • Hash Table
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “majority element” problem by leveraging the C++ Standard Library algorithm nth_element. The method receives a mutable reference to a vector of integers, rearranges the elements such that the element at the middle position is the one that would appear there in a fully sorted array, and then returns that element. Because a majority element is defined as an element appearing more than half the time, it is guaranteed to occupy the middle index after partitioning, making this approach both concise and efficient.

Key Steps

Determining the middle index

auto mid = nums.size() / 2;

The code computes the integer division of the vector’s size by two, yielding the index that separates the lower half from the upper half of the collection. This index is central to the subsequent partitioning operation.

Partitioning with nth_element

nth_element(nums.begin(), nums.begin() + mid, nums.end());

nth_element rearranges the elements in the range [nums.begin(), nums.end()) so that the element positioned at nums.begin() + mid is exactly the element that would appear at that position in a fully sorted sequence. All elements before this position are guaranteed to be less than or equal to it, while all elements after are greater than or equal to it. The algorithm performs this rearrangement in-place, avoiding additional memory allocation.

Returning the candidate majority element

return nums[mid];

After the partitioning step, the element at the computed middle index is returned directly. If a majority element exists, it must be present at this position, satisfying the problem’s requirement.

Edge Cases Handled

When the input vector contains an odd number of elements, the middle index points to the exact central element, and nth_element ensures that this element reflects the median of the sorted order. For an even number of elements, integer division discards the fractional part, selecting the lower of the two central positions. In both scenarios, if a value appears more than half the time, it will occupy the selected middle position after partitioning, guaranteeing correct identification.

The algorithm also gracefully handles vectors where all elements are identical. In such cases, the partitioning step leaves the vector unchanged, and the returned element is trivially the majority element. Similarly, when the vector contains a diverse set of values but still includes a majority element, the partitioning isolates that element at the middle index without needing to examine the entire ordering.

Performance Optimizations

The use of nth_element is a deliberate optimization. Unlike a full sort, which would require O(n log n) operations, nth_element achieves the necessary positioning in linear average time, reducing the overall computational workload. Because the algorithm works directly on the input vector, it avoids allocating auxiliary containers, thereby minimizing memory overhead. The in-place nature of the operation also improves cache locality, as the data remains contiguous throughout the process. These characteristics collectively contribute to a solution that is both time-efficient and memory-conservative while maintaining clear and readable code.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big bucket full of different colored blocks, and you want to find the color that shows up more than any other. Because there are so many blocks, it would take a long time to count every single one. Instead, it is much faster to mix them all up and look right at the middle of the pile.

The computer does this by taking the whole collection of numbers and shuffling them around until the ones that are smaller are on the left and the ones that are bigger are on the right. Once the numbers are organized this way, the secret to finding the most common one is to peek at the exact center of the line. Because the number you are looking for appears so often, it is guaranteed to be sitting right there in the middle spot after the rearranging is finished. It is just like finding a favorite toy in the center of a pile after tidying up.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.08 | σ = 1.49

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Rust JS Java Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
zfang399 C++
55 links | 37 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Majority Element - Leetcode 169 - Python'
NeetCode 15 mins
Majority Element - Leetcode 169 - Python
YouTube video 'Leetcode | 169. Majority Element | Easy | Java Solution'
Developer Docs 5 mins
Leetcode | 169. Majority Element | Easy | Java Solution
YouTube video 'LeetCode 169: Majority Element | Boyer-Moore Majority Voting Algorithm'
Engineering Digest 9 mins
LeetCode 169: Majority Element | Boyer-Moore Majority Voting Algorithm
YouTube video '24. Majority Element | Leetcode 169 | Moore's Voting algorithm | Day-21'
Ayushi Sharma 18 mins
24. Majority Element | Leetcode 169 | Moore's Voting algorithm | Day-21
YouTube video 'Majority Element - LeetCode 169  - Python  #leetcode #majorityelement #votingalgorithm'
Deepti Talesra 10 mins
Majority Element - LeetCode 169 - Python #leetcode #majorityelement #votingalgorithm
YouTube video 'Can You Find Majority Element (LeetCode 169: Majority Element)'
Code With Zi 7 mins
Can You Find Majority Element (LeetCode 169: Majority Element)
YouTube video 'MAJORITY ELEMENT | LEETCODE 169 | PYTHON SOLUTION'
Cracking FAANG 9 mins
MAJORITY ELEMENT | LEETCODE 169 | PYTHON SOLUTION
YouTube video 'Majority Element - LeetCode 169 - Blind 75 - Coding Interview'
One Code Man 4 mins
Majority Element - LeetCode 169 - Blind 75 - Coding Interview
YouTube video 'How to Solve "169 Majority Element" on LeetCode? - Javascript (Hash Table)'
Becoming A Better Dev (with David) 6 mins
How to Solve "169 Majority Element" on LeetCode? - Javascript (Hash Table)
YouTube video 'LeetCode 169: Majority Element [Python]'
Frederik Müller 8 mins
LeetCode 169: Majority Element [Python]
YouTube video '169. Majority Element | February | Java | C++'
Mayur Programming Club 16 mins
169. Majority Element | February | Java | C++
YouTube video 'Majority Element | Leetcode 169 | Live coding session 🔥🔥| 3 Approaches | Moore voting algorithm'
Coding Decoded 14 mins
Majority Element | Leetcode 169 | Live coding session 🔥🔥| 3 Approaches | Moore voting algorithm
YouTube video 'LeetCode 169. Majority Element'
Happy Coding 24 mins
LeetCode 169. Majority Element
YouTube video 'Leetcode | Top Interview 150 | Easy | 169. Majority Element | Time: O(N) | Javascript'
Software Interviews Prep 9 mins
Leetcode | Top Interview 150 | Easy | 169. Majority Element | Time: O(N) | Javascript
YouTube video '169. Majority Element | Leetcode | Arrays | Fundamentals'
Coding with Tamilarasan 7 mins
169. Majority Element | Leetcode | Arrays | Fundamentals
YouTube video 'Solving LeetCode 169. Majority Element | Boyer-Moore Voting Algorithm | Google Interview Question'
Code Harmony 18 mins
Solving LeetCode 169. Majority Element | Boyer-Moore Voting Algorithm | Google Interview Question
YouTube video 'Daily Leetcode #692: Feb 21, 2022 - 169. Majority Element'
Programming Live with Larry 4 mins
Daily Leetcode #692: Feb 21, 2022 - 169. Majority Element
YouTube video 'Daily Leetcode #1413: Feb 12, 2024 - 169. Majority Element'
Programming Live with Larry 5 mins
Daily Leetcode #1413: Feb 12, 2024 - 169. Majority Element
YouTube video 'LeetCode 169 | Majority Element | Sorting | Counting | Divide and conquer | Java'
Sleepy Cracker 11 mins
LeetCode 169 | Majority Element | Sorting | Counting | Divide and conquer | Java
YouTube video 'LeetCode 169: Majority Element | C# Solution | Boyer-Moore Voting Algorithm'
Code Scribbler 7 mins
LeetCode 169: Majority Element | C# Solution | Boyer-Moore Voting Algorithm
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality