Majority Element-II

Arrays FAQs(Hard) Hard
  • Fun Fact: The underlying concept used in solving this problem is frequently applied in data analytics and database management
  • For instance, in a system where it is necessary to detect the most common elements in a data set, like finding the most popular products in a shopping app or detecting spam or malicious activities, solutions to this problem can be used
  • Similarly, social networking applications utilize this concept to discover trending hashtags or posts that are being shared more frequently
  • It's a simple, but incredibly powerful concept used in many areas of software development

Given an integer array nums of size n. Return all elements which appear more than n/3 times in the array. The output can be returned in any order.

Examples:

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

Output: [1]

Explanation: Here, n / 3 = 6 / 3 = 2.

Therefore the elements appearing 3 or more times is : [1]

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

Output: [1, 2]

Explanation: Here, n / 3 = 7 / 3 = 2.

Therefore the elements appearing 3 or more times is : [1, 2]

Input: nums = [1, 2, 1, 1, 3, 2, 2, 3](Give the solution sorted in ascending order)

Constraints

  • n == nums.length.
  • 1 <= n <= 105
  • -104 <= nums[i] <= 104

Hints

  • Use two counters to track two potential majority candidates. Count occurrences using a hash map (O(n) space). Collect elements that appear more than n/3 times.
  • "Sort the array (O(n log n)). Scan linearly to find elements occurring more than n/3 times."

Company Tags

Ernst & Young Oracle Red Hat MongoDB Bungie KPMG Roblox Lyft Bain & Company Flipkart Cloudflare Robinhood Pinterest Freshworks Reddit Electronic Arts Salesforce HashiCorp Unity Technologies Micron Technology AMD Splunk McKinsey & Company Shopify Qualcomm Google Microsoft Amazon Meta Apple Netflix Adobe