
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.
1function majorityElement(nums) {
2 const countMap = {};
3 const limit = Math.floor(nums.length / 3);
4 for (const num of nums) {
5 countMap[num] = (countMap[num] || 0) + 1;
6 }
7 return Object.keys(countMap).filter(num => countMap[num] > limit).map(Number);
8}
9
10// Example usage
11const nums = [3, 2, 3];
12console.log(majorityElement(nums));This JavaScript solution utilizes a plain object as a hashmap to count the occurrences of each number. Once the counts are recorded, an Object.keys method retrieves the keys, after which we filter based on the count being greater than ⌊n/3⌋ and map the keys back to numbers since keys are strings.
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 Java implementation follows Boyer-Moore logic for tracking two majority candidates with constant space, confirming by counting occurrences a second time that potential candidates truly appear >⌊n/3⌋.