v9.1.1
Menu

Majority Element

easyFREEArrays & HashingNetflix DSA

Given an array nums, return the majority element (appears more than n/2 times). The majority element always exists.

Example

Input
3,2,3
Output
3
Reasoning
  • nums is a list of integers. Here it is 3, 2, 3, so there are n=3n = 3 values.
  • The majority element is the value whose count is strictly greater than n2=32=1.5\frac{n}{2} = \frac{3}{2} = 1.5.
  • Tally the values: 3 appears 22 times and 2 appears 11 time. Since 2>1.52 > 1.5, 3 qualifies, while 1<1.51 < 1.5 rules out 2.
  • The output is that single value, 3, returned as an integer, not its count.
  • Notice that at most one value can ever clear the bar: if two different values each appeared more than n2\frac{n}{2} times, together they would need more than nn slots. That is why the answer is always unique, and why "more than half" is a stronger condition than simply "most frequent".

Constraints

  • 1 <= len(nums) <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9

More from Netflix DSA

solution.py

Test results

Sign in to run your code against the test cases.