
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.
- Array length n = 3, so ⌊n/3⌋ = 1.
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.
- Array length n = 1, so ⌊n/3⌋ = 0.
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
Editorial
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. |
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