Top MNC interview question which will be very useful for beginners to crack the interview and for there future careers

test

Breaking

Post Top Ad

Your Ad Spot

Saturday, December 19, 2020

Google Interview Question(Majority Element in the given Array)

Question:

Find the Majority Element in the given Array

Explanation:

We need to find the majority element in a given array which should be optimal and less time of execution.

For Example:

    Array[10,8,9,9,9,9,10,4,3]

    Result:9

Program:

#include <iostream>
using namespace std;

int majorElem(int arr[], int size){

    int major=0,count=1;
    for(int i=1;i<size;i++){

        if(arr[i]==arr[major]){

            count++;
        }
        else{

            count--;
        }
        if(count==0){

            major=i;
            count=1;
        }
    }
    return arr[major];
}
int main(){

    int arr[]={10,8,9,9,9,9,10};
    int result=majorElem(arr,7);
    cout<<"Your majority Element  "<<result<<endl;
}
---------End---------

Post Top Ad

Your Ad Spot