---
tags: data_structure_python
---
# Majority Element <img src="https://img.shields.io/badge/-easy-brightgreen">
Given an array of size n, find the majority element. The majority element is the element that appears **more than** ```⌊ n/2 ⌋``` times.
You may assume that the array is non-empty and the majority element always exist in the array.
<ins>**Example 1:**</ins>
```
Input: [3,2,3]
Output: 3
```
<ins>**Example 2:**</ins>
```
Input: [2,2,1,1,1,2,2]
Output: 2
```
# Solution
### Solution 1: First attempt
```python=
class Solution:
def majorityElement(self, nums: List[int]) -> int:
# O(n) time complexity.
# O(n) space complexity.
dic = {}
m = len(nums)//2
for elt in nums:
if not elt in dic:
dic[elt] = 1
else:
dic[elt] += 1
if dic[elt] > m:
return elt
return nums[0]
```
### Solution 2: Boyer-Moore Voting Algorithm
```python=
class Solution:
def majorityElement(self, nums: List[int]) -> int:
# O(n) time complexity.
# O(1) space complexity.
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
```