tutorialcup
Majority Element II Leetcode Solution
In this problem, we are given an array of integers. The goal is to find all the elements which occur more than ⌊N / 3⌋ time in the array where N = size of the array and ⌊ ⌋ is the floor operator. We need to return an array of such elements.
Range of elements: -10^9 to 10^9
Example
Array = {1 , 2 , 3 , 3 , 2}
2 3
Explanation: ⌊N / 3⌋ = ⌊5 / 3⌋ = 1. Now, the integers 2 and 3 have frequencies equal to 2, which is greater 1. So, we print them.
Array = {1 , 2 , 3 , 4}
No majority elements
Explanation: We did not find any element whose frequency is greater than 1 in this case. So, we print "No Majority elements".
Approach(Storing Frequencies)
As the title suggests, we can store the frequency of every element in the array using a hash table and then check for elements having a frequency greater than ⌊N / 3⌋. In this way, we can find all elements that satisfy the condition.
Algorithm
- Initialize a HashMap-frequency to store the frequencies of elements in the array and a list/vector result to store the majority elements
- For every element i in the array:
- Increment its frequency: frequency++(or set as 1 if not present already)
- For every key in the hashmap:
- If frequency > N / 3
- Add it to the result
- Return the list result
Implementation of Majority Element II Leetcode Solution
C++ Program
#include
using namespace std;
vector majorityElement(vector& a)
{
int N = a.size();
www.tutorialcup.com/leetcode-solutions/majority-element-i...
Majority Element II Leetcode Solution
In this problem, we are given an array of integers. The goal is to find all the elements which occur more than ⌊N / 3⌋ time in the array where N = size of the array and ⌊ ⌋ is the floor operator. We need to return an array of such elements.
Range of elements: -10^9 to 10^9
Example
Array = {1 , 2 , 3 , 3 , 2}
2 3
Explanation: ⌊N / 3⌋ = ⌊5 / 3⌋ = 1. Now, the integers 2 and 3 have frequencies equal to 2, which is greater 1. So, we print them.
Array = {1 , 2 , 3 , 4}
No majority elements
Explanation: We did not find any element whose frequency is greater than 1 in this case. So, we print "No Majority elements".
Approach(Storing Frequencies)
As the title suggests, we can store the frequency of every element in the array using a hash table and then check for elements having a frequency greater than ⌊N / 3⌋. In this way, we can find all elements that satisfy the condition.
Algorithm
- Initialize a HashMap-frequency to store the frequencies of elements in the array and a list/vector result to store the majority elements
- For every element i in the array:
- Increment its frequency: frequency++(or set as 1 if not present already)
- For every key in the hashmap:
- If frequency > N / 3
- Add it to the result
- Return the list result
Implementation of Majority Element II Leetcode Solution
C++ Program
#include
using namespace std;
vector majorityElement(vector& a)
{
int N = a.size();
www.tutorialcup.com/leetcode-solutions/majority-element-i...