CA 21 - Find the Majority Element

 

Majority Element

Difficulty: MediumAccuracy: 27.82%Submissions: 813K+Points: 4Average Time: 59m

Given an array arr[]. Find the majority element in the array. If no majority element exists, return -1.

Note: A majority element in an array is an element that appears strictly more than arr.size()/2 times in the array.

Examples:

Input: arr[] = [1, 1, 2, 1, 3, 5, 1]
Output: 1
Explanation: Since, 1 is present more than 7/2 times, so it is the majority element.
Input: arr[] = [7]
Output: 7
Explanation: Since, 7 is single element and present more than 1/2 times, so it is the majority element.
Input: arr[] = [2, 13]
Output: -1
Explanation: Since, no element is present more than 2/2 times, so there is no majority element.

Constraints:
1 ≤ arr.size() ≤ 105
1 ≤ arr[i] ≤ 105








MY CODE:


class Solution:

    def majorityElement(self, arr):

        a=0

        c=None


        for i in arr:

            if a==0:

                c=i

            if i==c:

                a+=1

            else:

                a-=1

        

        if arr.count(c) > len(arr)//2:

            return c

        return -1

Comments

Popular posts from this blog

CA 22 - Reverse a Linked List