Tutorialspoint
Problem
Solution
Submissions

Majority Element II

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find all elements that appear more than ⌊n/3⌋ times in an array, where n is the length of the array. The algorithm should run in linear time and use only constant extra space. There can be at most 2 such elements in any array.

Example 1
  • Input: nums = [3,2,3]
  • Output: [3]
  • Explanation:
    • Array length n = 3, so ⌊n/3⌋ = 1.
    • Element 3 appears 2 times, which is > 1.
    • Element 2 appears 1 time, which is not > 1.
    • Therefore, only [3] appears more than ⌊n/3⌋ times.
Example 2
  • Input: nums = [1]
  • Output: [1]
  • Explanation:
    • Array length n = 1, so ⌊n/3⌋ = 0.
    • Element 1 appears 1 time, which is > 0.
    • Therefore, [1] appears more than ⌊n/3⌋ times.
Constraints
  • 1 ≤ nums.length ≤ 5 * 10^4
  • -10^9 ≤ nums[i] ≤ 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(1)
  • At most 2 elements can appear more than ⌊n/3⌋ times
ArraysAlgorithmsIBMEY
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Boyer-Moore Majority Vote algorithm extended for finding 2 candidates
  • Maintain two candidates and their respective counts
  • In the first pass, find potential candidates using voting mechanism
  • In the second pass, verify if candidates actually appear more than n/3 times
  • If a number matches candidate1, increment count1; if matches candidate2, increment count2
  • If neither matches and both counts > 0, decrement both counts

Steps to solve by this approach:

 Step 1: Initialize two candidate variables and their respective count variables to 0
 Step 2: First pass through array - use voting mechanism to find potential candidates
 Step 3: If current element matches candidate1, increment count1; if matches candidate2, increment count2
 Step 4: If no match and count1 is 0, set candidate1 to current element; if count2 is 0, set candidate2
 Step 5: If no match and both counts > 0, decrement both counts (voting mechanism)
 Step 6: Second pass through array - count actual occurrences of both candidates
 Step 7: Add candidates to result array only if their count exceeds n/3 threshold

Submitted Code :