Majority Element
Updated
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[]) → intExamples
Example 1
nums = [3,2,3]return = 3The value 3 appears twice in an array of length 3.
Example 2
nums = [2,2,1,1,1,2,2]return = 2The value 2 appears four times, which is more than half of 7.
Example 3
nums = [-1,-1,-1,2,3]return = -1The 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 Onsite Interview questions
- Bad Request AlertsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Count Index Pairs with Equal Value OffsetGoogle · ONSITE INTERVIEWGoogle interview questions
- Net Position Calculation from API SnapshotsHeadlands Technologies · ONSITE INTERVIEWHeadlands Technologies interview questions
- Square Each Array ValueAMD · ONSITE INTERVIEWAMD interview questions
- Max Points on a LineLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Group-Relative Policy AdvantagesAmazon · ONSITE INTERVIEW
- Product Total With the Cheapest PromotionInstacart · ONSITE INTERVIEWInstacart interview questions
- Equation Tuple CombinationZoox · ONSITE INTERVIEW
- Unique Near-Equal Target-Sum PairsFivetran · ONSITE INTERVIEWFivetran interview questions
- Minimum Unique Card Suffix LengthBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Count Pairs Divisible by KApple · ONSITE INTERVIEWApple interview questions