Skip to content

Commit d24bb8f

Browse files
committed
Find the Majority Element in the Array
1 parent 6ed4c25 commit d24bb8f

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

Majoirty_Eelement.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""
2+
Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.
3+
4+
Input:
5+
The first line of the input contains T denoting the number of testcases. The first line of the test case will be the size of array and second line will be the elements of the array.
6+
7+
Output:
8+
For each test case the output will be the majority element of the array. Output "-1" if no majority element is there in the array.
9+
10+
User Task:
11+
The task is to complete the function findMajority() which finds the majority element in the array. If no majority exists, return -1.
12+
13+
Expected Time Complexity: O(N).
14+
Expected Auxiliary Space: O(1).
15+
16+
Constraints:
17+
1 <= T<= 100
18+
1 <= N <= 107
19+
0 <= Ai <= 106
20+
21+
Example:
22+
Input:
23+
2
24+
5
25+
3 1 3 3 2
26+
3
27+
1 2 3
28+
29+
Output:
30+
3
31+
-1
32+
33+
Explanation:
34+
Testcase 1: Since, 3 is present more than N/2 times, so it is the majority element.
35+
Testcase 2: Since, each element in {1,2,3} appears only once so there is no majority element.
36+
"""
37+
38+
39+
# Complete this function
40+
def majorityElement(A, N):
41+
# Your code here
42+
weight_dict = {}
43+
for elem in A:
44+
if elem not in weight_dict.keys():
45+
weight_dict[elem] = 1
46+
else:
47+
weight_dict[elem] += 1
48+
49+
for item, weight in weight_dict.items():
50+
if weight > int(N / 2):
51+
return item
52+
return -1
53+
54+
55+
# {
56+
# Driver Code Starts
57+
# Initial Template for Python 3
58+
59+
import math
60+
61+
from sys import stdin
62+
63+
64+
def main():
65+
T = int(input())
66+
while T > 0:
67+
N = int(input())
68+
69+
A = [int(x) for x in input().strip().split()]
70+
71+
print(majorityElement(A, N))
72+
73+
T -= 1
74+
75+
76+
if __name__ == "__main__":
77+
main()
78+
# } Driver Code Ends

0 commit comments

Comments
 (0)