Majority Element: Easy Problem, Sneaky Insight
dev.to·1d·
Discuss: DEV
🎯Performance Proofs
Preview
Report Post

The Majority Element problem on LeetCode looks like one of those questions you expect to solve in two minutes and immediately forget about.

Input: an array of numbers Output: the number that appears more than n/2 times (n is the size of the array)

That’s it. No tricks hiding in the corner.

LeetCode even tells you upfront: 👉 “The majority element always exists.”

So your brain does the obvious thing:

“Cool. I’ll just count.”

99% of the time, that’s exactly the right instinct.


The Obvious Solution (And Why It’s Perfectly Fine)

You loop through the array, count how many times each number appears, and return the one whose count is greater than n/2.

Example:

Input:  [1, 1, 2, 2, 2, 3, 3]
Counts: {1: 2, 2: 3, 3: 2}

2 app…

Similar Posts

Loading similar posts...