Majority Element - aloalgo

Majority Element

Easy

You are given an array nums of size n.

Your task is to identify and return the majority element from this array.

You may assume that:

  • The input array nums will always be non-empty.
  • A majority element will always exist within the array.
  • The majority element is defined as the element that appears strictly more than n / 2 times.

Return the majority element.

Example 1

Input
[1, 2, 1]
Output
1
Explanation:

The array contains 2 ones and 1 two. The length is 3. n/2 = 1.5. The number 1 appears 2 times, which is more than 1.5.

Example 2

Input
[2, 2, 1, 1, 1, 2, 2]
Output
2
Explanation:

The array contains 4 twos and 3 ones. The length is 7. n/2 = 3.5. The number 2 appears 4 times, which is more than 3.5.

Example 3

Input
[3, 3, 4, 5, 4, 5, 2, 1, 3, 3, 3]
Output
3
Explanation:

The array contains 5 threes, 2 fours, 2 fives, 1 two, and 1 one. The length is 11. n/2 = 5.5. The number 3 appears 5 times, which is more than 5.5.

Loading...
Input
[1, 2, 1]
Output
1

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!