Find the only element that appears b times using C++


In this problem, we are given an arr[] of size n and two integers a and b. Our task is to find the only element that appears b times.

All values of the array occur a time except one value which occurs b times in the array and we need to find that value.

Let’s take an example to understand the problem,

Input

arr[] = {3, 3, 3, 3, 5, 5, 5, 1, 1,1,1} a = 4, b = 3

Output

5

Solution Approach

A simple solution to the problem is by counting the occurrence of each element and then storing it in a 2D matrix. Then traversing the matrix to find the value with occurrence frequency b.

The time complexity of this approach is O(N2) but a more effective approach that can solve the problem is by finding the sum of all unique elements of the array and then multiplying it by a. Then subtract the sum of the whole array from this value and then divide the result by (a-b). The resulting value is the value whose occurrence frequency is b.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
int findbFreqVal(int arr[], int n, int a, int b){
   unordered_set<int> uniqueVal;
   int uniqueValSum = 0, arrSum = 0;
   for (int i = 0; i < n; i++) {
      if (uniqueVal.find(arr[i]) == uniqueVal.end()) {
         uniqueVal.insert(arr[i]);
         uniqueValSum += arr[i];
      }
      arrSum += arr[i];
   }
   uniqueValSum = a * uniqueValSum;
   return ((uniqueValSum - arrSum) / (a - b));
}
int main(){
   int arr[] = { 4, 4, 4, 31, 8, 8, 8, 5, 5, 5};
   int a = 3, b = 1;
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The value of the array that appears b times is "<<findbFreqVal(arr, n, a, b);
   return 0;
}

Output

The value of the array that appears b times is 31

Updated on: 11-Feb-2022

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements