5.Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

Solution I: (Using Sorting)

class Solution
{
public:
    int majorityElement(vector<int> &nums)
    {

        int res = -1, count = 0;
        sort(nums.begin(), nums.end());
        int i = 0;
        while (i < nums.size() - 1)
        {
            if (nums[i] == nums[i + 1])
            {
                count++;
            }
            else
            {
                if (count + 1 > (nums.size() / 2))
                {
                    res = nums[i];
                }
                count = 0;
            }
            i++;
        }

        if (count + 1 > (nums.size() / 2))
        {

            res = nums[i];
        }

        return res;
    }
};

Time Complexity: O(n log(n) ) , Space Complexity: O(1)

Solution II: (Using Hashmaps)

Time Complexity: O(n) , Space Complexity: O(n)

Solution III: (Optimized Solution using Moore's Voting Algo )

Time Complexity: O(n) , Space Complexity: O(1)

Last updated

Was this helpful?