Skip to content

Commit 1f7a709

Browse files
author
Joseph Luce
authored
Create 169_majority_element.md
1 parent a609354 commit 1f7a709

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# 169. Majority Element
2+
3+
## Solution with dictionary
4+
- Runtime: O(N)
5+
- Space: O(N)
6+
- N = Number of elements in array
7+
8+
Fairly straight forward, use a dictionary to count the number of occurrences for each number. Then compare it to the current best.
9+
10+
```
11+
from collections import defaultdict
12+
13+
class Solution:
14+
def majorityElement(self, nums: List[int]) -> int:
15+
counter = defaultdict(lambda: 0)
16+
curr_major, curr_count = None, 0
17+
for n in nums:
18+
counter[n] += 1
19+
if counter[n] > curr_count:
20+
curr_major = n
21+
curr_count = counter[n]
22+
return curr_major
23+
```
24+
25+
## Solution with constant space
26+
- Runtime: O(N)
27+
- Space: O(1)
28+
- N = Number of elements in array
29+
30+
Keeping a dictionary of occurrences when you just want to find one major element is performing extra work.
31+
You can instead pass through the array once while keeping track of your current major number and any other number is a reason your current major number should be decremented, else increment it.
32+
Once your current major number's count reaches zero, then it is a reason a new major number takes its place.
33+
34+
```
35+
class Solution:
36+
def majorityElement(self, nums: List[int]) -> int:
37+
curr_major, curr_count = None, 0
38+
for n in nums:
39+
if curr_major != n:
40+
curr_count -= 1
41+
else:
42+
curr_count += 1
43+
if curr_count <= 0:
44+
curr_major, curr_count = n, 1
45+
return curr_major
46+
```

0 commit comments

Comments
 (0)