problem no 73:find the first element to occur k times inside an array.

 problem statement:

Given an array of N integers. Find the first element that occurs K number of times. 
 

Example 1:

Input :
N = 7, K = 2
A[] = {1, 7, 4, 3, 4, 8, 7}
Output :
4
Explanation:
Both 7 and 4 occur 2 times. 
But 4 is first that occurs 2 times.

 

Your Task:  
You don't need to read input or print anything. Your task is to complete the function firstElementKTime() which takes the array A[], its size and an integer as inputs and returns the required answer. If answer is not present in the array, return -1.



code:


 int firstElementKTime(int a[], int n, int k)

    {

        map<int,int> mapp;

        int got=0;

        int z=0;

        for(int i=0;i<n;i++)

        {

            mapp[a[i]]++;

            

            for(auto ele:mapp)

            {

                if(ele.second==k)

                {

                    z=ele.first;

                    got=1;

                    break;

                }

            }

            if(got==1)

            {

                break;

            }

        }

        if(got==0)

        {

            return -1;

        }

        return z;

        

    }

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.