Find sum of factorials in an array in C++


Consider we have an array A, which is sorted. It has all elements appears twice, but one element is present for only one time. We have to find that element. If the array is [1, 1, 3, 3, 4, 4, 5, 6, 6, 7, 7, 9, 9], so the single element is 5.

We will use the binary search approach to solve this. All elements before the single element has their first occurrence at index 0, 2, 4, … and first occurrence at index 1, 3, 5, … but after the single element, all occurrences of the first number will be at odd index, and second element will be at even index positions.

So first find the middle index mid, if mid is even, then compare A[mid] and A[mid + 1], if both are same, then go to the left or right as required. Otherwise when the mid is odd, then compare A[mid] and A[mid – 1], if they are same, then go to the left or right as required.

Example

#include<iostream>
using namespace std;
void findSingleElement(int *arr, int left, int right) {
   if (left > right)
      return;
   if (left==right) {
      cout << "The required element is: "<< arr[left];
      return;
   }
   int mid = (left + right) / 2;
   if (mid%2 == 0) {
      if (arr[mid] == arr[mid+1])
         findSingleElement(arr, mid+2, right);
      else
         findSingleElement(arr, left, mid);
   }else{
      if (arr[mid] == arr[mid-1])
         findSingleElement(arr, mid+1, right);
      else
         findSingleElement(arr, left, mid-1);
   }
}
int main() {
   int arr[] = {1, 1, 3, 3, 4, 4, 5, 6, 6, 7, 7, 9, 9};
   int len = sizeof(arr)/sizeof(arr[0]);
   findSingleElement(arr, 0, len-1);
}

Output

The required element is: 5

Updated on: 04-Nov-2019

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements