Logical Reasoning

Question 2

You have an array of n elements, and you have to find the majority element in that array.

  • Majority Element is the element that occurs more than (size/2) times in the given array

Input Format

  • First line will contain an integer size denoting the length of the array.
  • Second line will contain (size-1) separated integers, denoting the elements of the array

Output Format

  • If there is a majority element in an array, the output will be Majority element is : number
  • If there is no majority element in the array, the output will be Majority Element is not present in the list.
Zoho Coding Question

Code for the above Problem

result= {}
count = []
size = int(input())
arr = list(map(int, input().split()))
for i in arr:
result[i] = arr.count(i)
for i in result.values():
count.append(i)
index = count.index(max(count))
if count[index] > size//2:
for key, value in result.items():
if (value == count[index]):
print("Majority element value is:",key)
else:
print("Majority element does not exist")
#include <iostream>
using namespace std;
int main()
{
    int  size,n;
    printf("Enter the size of the array\n");
    scanf("%d",&size);
    int arr[size];
    printf("Enter the elements of the array\n");
    for(n=0;n<size;n++)
    {
        scanf("%d",&arr[n]);
    }
    findMajority(arr, size);
    return 0;
}
void findMajority(int arr[], int size)
{
    int maxCount = 0;
    int index = -1;
    for(int i = 0; i < size; i++)
    {
        int count = 0;
        for(int j = 0; j < size; j++)
        {
            if(arr[i] == arr[j])
            count++;
        }
        if(count > maxCount)
        {
            maxCount = count;
            index = i;
        }
    }

    if (maxCount > size/2)
       cout << "Majority element is " <<arr[index] << endl;
    else
        cout << "Majority Element does not exist" << endl;
}
Output
Enter the size of the array
9
Enter the elements of the array
1 2 3 4 5 5 5 5 5
Majority element is 5