Skip to content

Commit de37840

Browse files
authored
Merge pull request #59 from NEHA-AMIN/feature/majority-element
Solution #169 - Neha Amin - 14/07/2025
2 parents a7250c7 + 417bc4c commit de37840

File tree

3 files changed

+180
-0
lines changed

3 files changed

+180
-0
lines changed
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
# 169. Majority Element
2+
3+
**Difficulty:** *Easy*
4+
**Category:** *Arrays, Hash Table, Divide and Conquer*
5+
**Leetcode Link:** [Problem Link](https://leetcode.com/problems/majority-element/)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
*Given an array nums of size n, return the majority element — the element that appears more than ⌊n / 2⌋ times.*
12+
13+
*Constraints typically include:<br>
14+
- It is guaranteed that the majority element always exists in the array.*
15+
16+
---
17+
18+
## 💡 Approach & Key Insights
19+
20+
*The problem centers on identifying an element that occurs more than n/2 times. Three approaches are commonly used:<br>
21+
- Brute-force with nested loops.<br>
22+
- Better approach using hash map frequency counting.<br>
23+
- Optimal approach using Moore’s Voting Algorithm for O(n) time and O(1) space.*
24+
25+
---
26+
27+
## 🛠️ Breakdown of Approaches
28+
29+
### 1️⃣ Brute Force / Naive Approach
30+
31+
- **Explanation:** *For each element, count its frequency using a nested loop. If any element occurs more than ⌊n/2⌋ times, return it.*
32+
- **Time Complexity:** O(n²) – due to nested iterations.
33+
- **Space Complexity:** O(1)
34+
- **Example/Dry Run:**
35+
36+
```plaintext
37+
Input: [3, 2, 3]
38+
Step 1: Check 3 → appears 2 times → not > 1.5
39+
Step 2: Check 2 → appears 1 time → not > 1.5
40+
Return 3
41+
```
42+
43+
---
44+
45+
### 2️⃣ Better Approach
46+
47+
- **Explanation:** *Use a hash map to store frequencies of each number. As you update counts, if any value exceeds ⌊n/2⌋, return it.*
48+
- **Time Complexity:** O(n) – single pass to count.
49+
- **Space Complexity:** O(n) – for storing frequencies.
50+
- **Example/Dry Run:**
51+
52+
```plaintext
53+
Input: [2, 2, 1, 1, 1, 2, 2]
54+
Count Map:
55+
{2: 1}
56+
{2: 2}
57+
{2: 2, 1: 1}
58+
...
59+
{2: 4, 1: 3}
60+
Check: 4 > floor(7/2) = 3 → return 2
61+
```
62+
63+
---
64+
65+
### 3️⃣ Optimal Approach
66+
67+
- **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.*
68+
- **Time Complexity:** O(n) – single pass.
69+
- **Space Complexity:** O(1) – constant space.
70+
- **Example/Dry Run:**
71+
72+
```plaintext
73+
Input: [2, 2, 1, 1, 1, 2, 2]
74+
Step-by-step:
75+
candidate = 2, count = 1
76+
2 == 2 → count = 2
77+
1 != 2 → count = 1
78+
1 != 2 → count = 0 → candidate = 1, count = 1
79+
1 == 1 → count = 2
80+
2 != 1 → count = 1
81+
2 != 1 → count = 0 → candidate = 2, count = 1
82+
Final candidate = 2 → return 2
83+
```
84+
85+
---
86+
87+
## 📊 Complexity Analysis
88+
89+
| Approach | Time Complexity | Space Complexity |
90+
| -------------------- | --------------- | ---------------- |
91+
| Brute Force | O(n²) | O(1) |
92+
| Hash Map Counting | O(n) | O(n) |
93+
| Moore’s Voting Algo | O(n) | O(1) |
94+
95+
---
96+
97+
## 📉 Optimization Ideas
98+
99+
*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.*
100+
101+
---
102+
103+
## 📌 Example Walkthroughs & Dry Runs
104+
105+
```plaintext
106+
Example: [3, 3, 4, 2, 4, 4, 2, 4, 4]
107+
Step-by-step:
108+
candidate = 3, count = 1
109+
3 == 3 → count = 2
110+
4 != 3 → count = 1
111+
2 != 3 → count = 0 → candidate = 2
112+
...
113+
Final candidate = 4 → verify by count = 5
114+
n = 9 → ⌊9/2⌋ = 4 → 5 > 4 → return 4
115+
```
116+
117+
---
118+
119+
## 🔗 Additional Resources
120+
121+
- [Moore's Voting Algorithm - GeeksforGeeks](https://www.geeksforgeeks.org/theory-of-computation/boyer-moore-majority-voting-algorithm/)
122+
123+
---
124+
125+
Author: Neha Amin <br>
126+
Date: 19/07/2025
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
int majorityElement(vector<int>& nums) {
4+
int n = nums.size();
5+
int cnt = 0;
6+
int el;
7+
8+
// Boyer-Moore Voting Algorithm
9+
for (int i = 0; i < n; i++) {
10+
if (cnt == 0) {
11+
cnt = 1;
12+
el = nums[i];
13+
} else if (nums[i] == el) {
14+
cnt++;
15+
} else {
16+
cnt--;
17+
}
18+
}
19+
20+
// Optional: Verify if the candidate is actually the majority
21+
int cnt1 = 0;
22+
for (int i = 0; i < n; i++) {
23+
if (nums[i] == el)
24+
cnt1++;
25+
}
26+
if (cnt1 > n / 2)
27+
return el;
28+
return -1;
29+
}
30+
};
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution:
2+
def majorityElement(self, nums: List[int]) -> int:
3+
n = len(nums)
4+
cnt = 0
5+
el = None
6+
7+
# Boyer-Moore Voting Algorithm
8+
for i in range(n):
9+
if cnt == 0:
10+
cnt = 1
11+
el = nums[i]
12+
elif nums[i] == el:
13+
cnt += 1
14+
else:
15+
cnt -= 1
16+
17+
# Optional: Verify if el is actually the majority element.
18+
cnt1 = 0
19+
for i in range(n):
20+
if nums[i] == el:
21+
cnt1 += 1
22+
if cnt1 > n // 2:
23+
return el
24+
return -1

0 commit comments

Comments
 (0)