Majority Element-I

Arrays FAQs(Hard) Hard
  • This kind of problem is frequent in data analytics applications such as marketing research and political polling where a determination needs to be made about the dominant preference expressed in a group of responses
  • It helps to categorize and understand large datasets and even widely in popularity algorithms used by social media platforms like Facebook or Twitter to detect trends or viral content faster
  • This algorithm lays the foundation of the Boyer-Moore Majority Voting algorithm, which is an efficient way to solve the problem with a time complexity of O(N) and a space complexity of O(1)

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