easy +10 pts

Majority Element Finder

Find the element that appears more than n/2 times in a list.

Write a function `majority_element(nums)` that takes a list of integers `nums` and returns the majority element. The majority element is the element that appears more than `len(nums) // 2` times. You may assume that the majority element always exists in the input list. For example, in `[3, 2, 3]`, the majority element is `3` because it appears 2 times, which is greater than `3 // 2 = 1`. In `[2, 2, 1, 1, 1, 2, 2]`, the majority element is `2` because it appears 4 times, which is greater than `7 // 2 = 3`. Implement the function to work for any list of integers, including empty? No, the input will always have at least one element. The function should return the majority element value.

Constraints

1 <= len(nums) <= 10^5 -10^9 <= nums[i] <= 10^9 It is guaranteed that a majority element exists.

Example

>>> majority_element([3, 2, 3])
3
>>> majority_element([2, 2, 1, 1, 1, 2, 2])
2
>>> majority_element([1])
1
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Count how many times each element appears, then pick the one with count > n/2.
You can use a dictionary to store frequencies.
After counting, loop through the dictionary and return the first key with count > n//2.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.