𝗟𝗲𝗲𝘁𝗰𝗼𝗱𝗲 𝟭𝟱𝟬 | 𝗗𝗮𝘆 𝟰: 𝗠𝗮𝗷𝗼𝗿𝗶𝘁𝘆 𝗘𝗹𝗲𝗺𝗲𝗻𝘁

Leetcode 169 asks you to find the majority element in an array. The majority element appears more than n / 2 times. We assume it always exists.

You can solve this in two ways.

Approach 1: The Map Method

This method uses a Map to count how many times each number appears.

Complexity:

Approach 2: Boyer-Moore Voting Algorithm

This is an optimized way to solve the problem using constant memory.

Think of the numbers as opposing teams. Every time a number meets a different number, they cancel each other out. Since the majority element appears more than half the time, it will always be the last one standing.

How it works:

Complexity:

Why it matters:

Both methods have a time complexity of O(n). However, the second approach uses much less memory. It does not need a Map. This makes it better for large datasets.

Source: https://dev.to/afuji/leetcode-150-day-4-majority-element-naive-vs-optimized-eo6