Menu
CoddyTech

Majority Element

EasyHashingpython iconjava iconcpp iconc iconjs icon+10

You get an array of integers nums of length n. One value appears in it more than n / 2 times, and that value is called the majority element. Return it. A value that fills more than half the array is always unique, so there is exactly one answer.

Function

majorityElement(nums: integer-array) → integer
numsinteger-array
the array of integers, with one value filling more than half of it
Returnsinteger
the value that appears more than n / 2 times

Constraints

  • 1 ≤ nums.length ≤ 104
  • -109 ≤ nums[i] ≤ 109
  • One value appears more than nums.length / 2 times.

Examples

Input
nums = [3, 9, 3, 3, 4]
Output
3
Explanation
3 appears three times in five elements. Three is more than 5 / 2 = 2.5, and 9 and 4 appear once each.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Can you find the majority element in O(n) time with O(1) extra memory, without sorting the array?

Reset code
def majorityElement(nums):
    # Write code here
Test cases

Case 1

Case 2

Input

nums = [3, 9, 3, 3, 4]

Expected

3