Number of occurrence

QUESTION

Given a sorted array C[] and a number X, write a function that counts the occurrences of X in C[].\n\nInput:\n\nThe first line of input contains an integer T denoting the number of test cases.\nThe first line of each test case is N and X, N is the size of array.\nThe second line of each test case contains N input C[i].\n\nOutput:\n\nPrint the counts the occurrence of X, if zero then print -1.\n\nConstraints:\n\n1 T 100\n1 N 300\n1 C[i] 500\n\nExample:\n\nInput:\n2\n7 2\n1 1 2 2 2 2 3\n7 4\n1 1 2 2 2 2 3\n\nOutput:\n4\n-1\n\nExplanation:\nIn first test case, 2 occurs 4 times in 1 1 2 2 2 2 3\nIn second test case, 4 is not present in 1 1 2 2 2 2 3.

“TESTCASE_1”: “2\n7 2\n1 1 2 2 2 2 3\n7 4\n1 1 2 2 2 2 3\n###—###SEPERATOR—###—\n4\n-1”, “TESTCASE_2”: “2\n5 4\n2 4 5 3 4 \n8 3\n0 0 1 1 1 3 3 3\n###—###SEPERATOR—###—\n2\n3”, “TESTCASE_3”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
 
// Returns number of times x occurs in arr[0..n-1]
int countOccurrences(int arr[], int n, int x)
{
    int res = 0;
    for (int i=0; i<n; i++)
        if (x == arr[i])
          res++;
   if(res==0)
     res=-1;
    return res;
}
 
// Driver code
int main()
{
  int t;
  cin>>t;
  while(t--)
  {
    int n, x;
    cin>>n>>x;
    int arr[n], i;
    for(i=0; i<n; i++)
      cin>>arr[i];
   
    cout << countOccurrences(arr, n, x)<<endl;
  }
    return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.