Wednesday, May 8, 2019

Find Mode

  • Problem Description

    Write a program to find the mode of a given list of integers. Mode of a number is defined as the number which is most frequently occurred. 
    For example: 

    L = {1,2,2,3} // Here mode is 2(most frequently occurred)

    It is possible that multiple answers are possible for a list. In that case print all possible answers in non-increasing order.

    Input:
    First Line of input contains an integer t representing the number of test cases, Where first line of each test case has an integers N - number of integers in list, Next line contains N integers.

    Output:
    print all the possible modes in non-increasing order.

    Constraints:
    1<=t<=100
    1<=N<100000
    1<=a[i]<=1000000
  • Test Case 1

    Input (stdin)
    3

    5

    1 1 1 1 2

    7

    2 2 3 3 4 4 4

    10

    1 1 1 1 1 1 4 4 4 4

    Expected Output
    1 4 1
  • Test Case 2

    Input (stdin)
    2

    3

    1 1 2

    7

    3 3 4 4 4 4 5

    Expected Output
    1 4
Solution


#include <stdio.h>
 
int main(){
int n,i,s,j;
scanf("%d", &n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&s);
        int a[s],b[1000000],max=0;
        for(j=0;j<s;j++)
        {
            scanf("%d",&a[j]);
        }
        for(j=0;j<1000000;j++)
        {
            b[j] = 0;
        }
        
        for(j=0;j<s;j++)
        {
            if(b[a[j]] == 0)
            {
                b[a[j]] = 1;
            }
            else
            {
                b[a[j]] = b[a[j]] + 1;
            }
        }
        for(j=0;j<1000000;j++)
        {
            if(b[j] >= max)
            {
                max = b[j];
            }
        }
        for(j=1000000;j>0;j--)
        {
            if(b[j] == max)
            {
                printf("%d ",j);
            }
                
        }
        
    }
return 0;
}

No comments:

Post a Comment

Parity

Problem Description Ram and Sita playing the parity game. Two types of parity are there. One is odd parity and next is even parity. Ram will...