
Sponsored
Sponsored
This approach leverages a hashmap to count the occurrences of each element in the input array. We iterate through the array once to populate the hashmap and then make another pass to find all elements whose count is greater than ⌊n/3⌋. While this method is straightforward and simple to implement, it uses extra space proportional to the number of unique elements.
Time Complexity: O(n), where n is the length of the array since we go through the list of numbers twice.
Space Complexity: O(n) to handle the possible maximum unique elements.
1from typing import List
2from collections import defaultdict
3
4def majorityElement(nums: List[int]) -> List[int]:
5 countMap = defaultdict(int)
6 limit = len(nums) // 3
7 for num in nums:
8 countMap[num] += 1
9 return [num for num, count in countMap.items() if count > limit]
10
11# Example Usage
12nums = [3, 2, 3]
13print(majorityElement(nums))This Python solution uses a defaultdict from the collections module to track counts of each element in the array. We make one pass to fill the dictionary with counts and another to determine which elements exceed the ⌊n/3⌋ criterion. Using defaultdict simplifies the counting logic by providing default values.
The Boyer-Moore Voting Algorithm is optimized for finding the majority element which appears more than n/2 times. Here, we extend it to handle the case for n/3 by maintaining up to two potential candidates, since at most two elements can qualify for appearing more than ⌊n/3⌋ times. In the first pass, we identify the element candidates by attempting to cancel them out against others. A second pass is required to confirm the counts of these candidates to ensure they appear more than ⌊n/3⌋ times.
Time Complexity: O(n), going through elements twice.
Space Complexity: O(1) as no additional space is needed apart from variables.
This JavaScript solution applies Boyer-Moore for one-pass candidate identification and another for finalizing counts, ensuring candidates exceeding ⌊n/3⌋ are validated and returned.