Majority Element-I

Arrays FAQs(Hard) Hard

Given an integer array nums of size n, return the majority element of the array.


The majority element of an array is an element that appears more than n/2 times in the array. The array is guaranteed to have a majority element.

Examples:

Input: nums = [7, 0, 0, 1, 7, 7, 2, 7, 7]

Output: 7

Explanation: The number 7 appears 5 times in the 9 sized array

Input: nums = [1, 1, 1, 2, 1, 2]

Output: 1

Explanation: The number 1 appears 4 times in the 6 sized array

Input: nums = [-1, -1, -1, -1]

Constraints

  • n == nums.length.
  • 1 <= n <= 105
  • -104 <= nums[i] <= 104
  • One value appears more than n/2 times.

Hints

  • Keep a count variable while iterating, Increase count when encountering the same candidate. Decrease count when encountering a different number. If count == 0, change candidate. The final candidate will be the majority element.
  • Recursively split the array into halves, find the majority element in each half, if both halves agree, return that element.

Company Tags

MongoDB GE Healthcare Zomato Lyft Zynga Swiggy Flipkart Walmart Uber Intel Micron Technology Optum Wayfair Red Hat Roblox Texas Instruments OYO Rooms PwC Instacart eBay Salesforce Epic Games Splunk Medtronic Bloomberg Google Microsoft Amazon Meta Apple Netflix Adobe