Skip to content

Commit 0eacbc3

Browse files
leetode 169
1 parent 1e2e692 commit 0eacbc3

1 file changed

Lines changed: 96 additions & 0 deletions

File tree

Leetcode/Leetcode_169.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
"""
2+
Problem: Majority Element
3+
4+
Given an array nums of size n, return the majority element.
5+
The majority element is the element that appears more than ⌊n/2⌋ times.
6+
7+
Approach:
8+
- Use a dictionary (hash map) to count the frequency of each element.
9+
- Return the element with the maximum frequency.
10+
11+
Example:
12+
Input: nums = [1, 2, 1, 1, 3, 2, 1]
13+
Output: 1
14+
"""
15+
16+
from typing import List
17+
18+
19+
class Solution:
20+
def majorityElement(self, nums: List[int]) -> int:
21+
"""
22+
Finds the majority element in the list.
23+
24+
Steps:
25+
1. Create a dictionary to store frequencies.
26+
2. Traverse the list and update counts.
27+
3. Find the element with maximum frequency.
28+
4. Return that element.
29+
"""
30+
31+
# Step 1: Initialize dictionary
32+
freq = {}
33+
34+
# Step 2: Count frequencies
35+
for num in nums:
36+
if num in freq:
37+
freq[num] += 1
38+
else:
39+
freq[num] = 1
40+
41+
# Step 3: Find element with highest frequency
42+
majority = max(freq, key=freq.get)
43+
44+
# Step 4: Return result
45+
return majority
46+
47+
48+
# -------------------- Execution Example --------------------
49+
if __name__ == "__main__":
50+
nums = [1, 2, 1, 1, 3, 2, 1]
51+
52+
solution = Solution()
53+
result = solution.majorityElement(nums)
54+
55+
print("Input:", nums)
56+
print("Majority Element:", result)
57+
58+
59+
"""
60+
Execution Walkthrough:
61+
62+
nums = [1, 2, 1, 1, 3, 2, 1]
63+
64+
Building frequency dictionary:
65+
1 → {1:1}
66+
2 → {1:1, 2:1}
67+
1 → {1:2, 2:1}
68+
1 → {1:3, 2:1}
69+
3 → {1:3, 2:1, 3:1}
70+
2 → {1:3, 2:2, 3:1}
71+
1 → {1:4, 2:2, 3:1}
72+
73+
max(freq, key=freq.get) → 1
74+
75+
Output:
76+
Majority Element: 1
77+
"""
78+
79+
80+
"""
81+
Time Complexity (T.C.):
82+
- Traversing array: O(n)
83+
- Finding max: O(n)
84+
Overall: O(n)
85+
86+
Space Complexity (S.C.):
87+
- Dictionary storage: O(n)
88+
Overall: O(n)
89+
"""
90+
91+
92+
"""
93+
Notes:
94+
- Easy and intuitive solution using hashing.
95+
- For interviews, also learn Boyer-Moore Voting Algorithm (O(1) space).
96+
"""

0 commit comments

Comments
 (0)