Majority Element LeetCode Solution

Here, We see Majority Element problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Majority Element LeetCode Solution

Majority Element LeetCode Solution

Problem Statement

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than [n / 2] times. You may assume that the majority element always exists in the array.

Example 1:
Input: nums = [3,2,3]
Output: 3

Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2

Majority Element Leetcode Solution C++

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size(), candidate, counter;
        srand(unsigned(time(NULL)));
        while (true) {
            candidate = nums[rand() % n], counter = 0;
            for (int num : nums) {
                if (num == candidate) {
                    counter++;
                }
            }
            if (counter > n / 2) {
                break;
            }
        }
        return candidate;
    }
};
Code language: C++ (cpp)

Majority Element Leetcode Solution Java

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}
Code language: Java (java)

Majority Element Leetcode Solution JavaScript

var majorityElement = function(nums) {
    var obj = {};
    
    for(var i = 0; i < nums.length; i++){
        obj[nums[i]] = obj[nums[i]] + 1 || 1;
        if(obj[nums[i]] > nums.length / 2)  return nums[i];
    }
};
Code language: JavaScript (javascript)

Majority Element Python Solution

class Solution(object):
    def majorityElement(self, nums):
        return sorted(nums)[len(nums)/2]
Code language: Python (python)
Scroll to Top