Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Brute force

O(N) Time and O(1) space

Code

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        int n = nums.size();
        n/=3;
        vector<int> ans;
        unordered_map<int,int> mp;
        for(int x:nums) mp[x]++;
        for(auto [x,f]:mp) {
            if(f>n) ans.push_back(x);
        }
        return ans;
    }
};

Moore’s Voting Algorithm

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums)
    {
        int cand1 = -1, cand2 = -1, cnt1 = 0, cnt2 = 0, n = nums.size();
        for (int x : nums) {
            if (x == cand1) cnt1++;
            else if (x == cand2) cnt2++;
            else if (cnt1 == 0) {
                cand1 = x;
                cnt1 = 1;
            } else if (cnt2 == 0) {
                cand2 = x;
                cnt2 = 1;
            } else {
                cnt1--, cnt2--;
            }
        }
        vector<int> ans;
        cnt1 = 0, cnt2 = 0;
        for (int x : nums) {
            if (x == cand1) cnt1++;
            else if (x == cand2) cnt2++;
        }
        if (cnt1 > n / 3) ans.push_back(cand1);
        if (cnt2 > n / 3) ans.push_back(cand2);
        return ans;
    }
};