Skip to main content

Majority Element

Question

What is the most frequently occurring element in a given array of integers?

Example 1
Input: [2,2,1,1,1,2,2]

Output: 2

Solution

all//Majority Element.py


def majority_element(nums):
count_map = {}

for num in nums:
if num in count_map:
count_map[num] += 1
else:
count_map[num] = 1

max_count = 0
result = None

for num, count in count_map.items():
if count > max_count:
max_count = count
result = num

return result

# Driver code
nums = [3, 2, 3]
print(majority_element(nums))