FastPrepMajority Element

Majority Element

Microsoft logoMicrosoft● EasyFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given a non-empty integer array nums, return its majority element.

The majority element appears more than floor(nums.length / 2) times. You may assume that such an element always exists.

Your solution must run in O(n) time and use O(1) extra space.

Function

majorityElement(nums: int[]) → int

Examples

Example 1

nums = [3,2,3]return = 3

The value 3 appears twice in an array of length 3.

Example 2

nums = [2,2,1,1,1,2,2]return = 2

The value 2 appears four times, which is more than half of 7.

Example 3

nums = [-1,-1,-1,2,3]return = -1

The majority value may be negative.

Constraints

  • 1 <= nums.length <= 100000
  • Every value fits in a signed 32-bit integer.
  • Exactly one value appears more than floor(nums.length / 2) times.

More Microsoft problems

See Microsoft hiring insights
public int majorityElement(int[] nums) {
    // Write your code here.
}
nums[3,2,3]
expected3
Checking account…