Majority Element LeetCode Solution

Last updated on March 9th, 2025 at 10:19 pm

Here, we see a Majority Element LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Array, Bit Manipulation, Divide and Conquer

Companies

Adobe, Zenefits

Level of Question

Easy

Majority Element LeetCode Solution

Majority Element LeetCode Solution

1. 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

2. Coding Pattern Used in Solution

The provided code uses following patterns:

  • Randomized Algorithm (C++)
  • Sorting (Java and Python)
  • Hash Map Counting (JavaScript)

These patterns are commonly used for problems involving majority elements or frequency counting.

3. Code Implementation in Different Languages

3.1 Majority Element 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;
    }
};

3.2 Majority Element Java

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

3.3 Majority Element 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];
    }
};

3.4 Majority Element Python

class Solution(object):
    def majorityElement(self, nums):
        return sorted(nums)[len(nums)/2]

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n²)O(1)
JavaO(n log n)O(1)
JavaScriptO(n)O(n)
PythonO(n log n)O(n)

Scroll to Top