Find if array has an element whose value is half of array sum in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr of sorted unique values. Our task is to find if array has an element whose value is half of array sum

Problem Description: For the array arr[], we need to find element x in the array such that the sum of all elements of array is equal to 2*X.

Let’s take an example to understand the problem,

Input: arr[] = {2, 4, 5, 6, 7}

Output: No

Explanation: 

Sum = 2 + 4 + 5 + 6 + 7 = 24

No element found.

Solution Approach: 

To solve the problem, we simply need to find the elements which is half of the sum of all elements of the array.

Algorithm:

Step 1: Find the sum of all elements of the array.

Step 2: if the sum value is odd, return -1.

Step 3: if sum value is even, find element x such that x*2 = sum.

Step 4: if element found, return 1.
Step 5: if element not found return -1.

For searching the element, we can use the binary search algorithm as it is sorted.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int checkForElement(int array[], int n) {

   int arrSum = 0;
   for (int i = 0; i < n; i++)
      arrSum += array[i];

   if (arrSum % 2)
   return -1;

   int start = 0;
   int end = n - 1;
   while (start <= end)
   {
      int mid = start + (end - start) / 2;
      if ( ( 2 * array[mid] ) == arrSum)
         return array[mid];      
      else if (( 2 * array[mid] ) > arrSum)
         end = mid - 1;      
      else
         start = mid + 1;
   }

   return -1;
}

int main() {

   int array[] = { 4, 5, 6, 7, 9 };
   int n = sizeof(array) / sizeof(array[0]);
   int x = checkForElement(array, n);
   if(x != -1)
    cout<<"Element found, value is "<<x;
   else
    cout<<"Element not found!";
   return 0;
}

Output −

Element not found!
raja
Published on 22-Jan-2021 13:50:00
Advertisements