🔍 Problem: Leet Code 169 – Majority Element

QUESTION:

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

Constraints:

  • n == nums.length

  • 1 <= n <= 5 * 10<sup>4</sup>

  • -10<sup>9</sup> <= nums[i] <= 10<sup>9</sup>


💡Approach:

  1. Initially, when I saw this question, it came to my mind that it is related to frequency of element that is the occurrence, as based on it only we decide we can decide whether it’s a majority element or not.

  2. Since I am coding in Java, I thought of using the fundamental concept of any programming language which is
    - Conditional Statements, to find frequency is greater than half of the array length and
    - HashMap, one of the important concepts studied with JCF (Java Collection Framework), to find frequencies of each element.

  3. Then, I started to put my logic into Java Code. Here’s the result.


💻My Code:

class Solution {
    public int majorityElement(int[] nums) {
        LinkedHashMap<Integer,Integer> hm = new LinkedHashMap<>();
        for(int temp : nums)
        hm.put(temp,hm.getOrDefault(temp,0)+1);
        for(Map.Entry<Integer,Integer> e : hm.entrySet()){
            if(e.getValue()>nums.length/2)return e.getKey();
        }
        return -1;
    }
}

🖥️Output:


⏱️Efficiency of the code:

  • Time Complexity-O(n)

  • Space Complexity-O(n)


🧠My Learnings:

  • HashMap and its methods

  • Conditional Statements


Tags:

#Java #Leetcode #ProblemSolving #DSA

1
Subscribe to my newsletter

Read articles from ARCHANA GURUSAMY directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ARCHANA GURUSAMY
ARCHANA GURUSAMY

👩‍💻 I'm Archana Gurusamy, a passionate 3rd-year B.Tech IT student on a mission to grow as a developer.I'm currently deep-diving into Data Structures & Algorithms using Java, while also exploring web development and real-world projects. I love solving coding challenges, building meaningful applications, and documenting my learning journey through technical blogs. I believe in learning in public — sharing my logic, code, and even my rough ideas as I grow. I'm actively working on building a strong IT profile while preparing for real world challenges.