Skip to main content

Majority Element

Easy
Data Structures and Algorithms
Editorial
Topics:
Array
Counting
Greedy

Implement Solution.majorityElement(nums), where nums is a non-empty array of integers. Let n be the number of elements in nums; an integer is a majority element when it occurs more than n / 2 times in the array.

A majority element is guaranteed to exist. Return that integer. The order of the elements in nums is otherwise unrestricted, and the returned value must be the element itself rather than its frequency.

Example 1:

Input: nums = [4,4,2,4,3,4,4]
Output: 4
Explanation: The value 4 occurs five times out of seven positions, which is more than half.

Example 2:

Input: nums = [-3,1,-3,2,-3,-3]
Output: -3
Explanation: The value -3 appears four times out of six positions, so it is the guaranteed majority.

Example 3:

Input: nums = [7]
Output: 7
Explanation: The only element appears once, which is more than half of the one-element array.

Constraints:

  • 1 <= nums.length <= 10^5
  • nums contains only integers
  • A majority element exists in nums
  • The majority element appears more than nums.length / 2 times

Need help or want more practice?

Practise in an interviewGet AI Coach help