DEV Community

Cover image for 45 Days of Leetcode - Majority Element - Day 4.1
Anas Dew
Anas Dew

Posted on

45 Days of Leetcode - Majority Element - Day 4.1

Hey dev! In case you don't know, I've started #45daysofleetcode and in these 45 days i'll be writing about two problems every day.

The problem, how I solved it and a bit of detailed explanation.

I'm sharing this progress with you so that you too can learn a bit of different perspective and have new solutions so hit like to join this journey.

I've chosen the best list of problems from medium to hard. That made lots of developers crack the interview.

Are you excited?

Today's Problem

Name
Majority Element

Description
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

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

Enter fullscreen mode Exit fullscreen mode

My Approach

We create a dictionary. And add each element to it but with how many times it occured in the list like {value:occurence}. For that we iterate through the list and check if the value is in dictionary: if it is, increase occurence of value by 1; else add that value to the dictionary with the value = 1. and then return the key of the maximum value in the dictionary.

Code

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        maj = {}
        for i in nums:
            if i in maj:
                maj[i] += 1
            else :
                maj[i] = 1
        return max(zip(maj.values(), maj.keys()))[1] 
Enter fullscreen mode Exit fullscreen mode

Let me know if you've any questions or suggestions!.

If you want full list of solutions, here's the list. Make sure you star the repository.

Follow to join this #45daysofleetcode
Bye!

Top comments (0)