Majority Element-II

Arrays FAQs(Hard) Hard

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