Divide array into two parts with equal sum according to the given constraints

Given an array arr[] of N integers, the task is to select an integer x (which may or may not be present in the array) and remove all of its occurrences from the array and divide the remaining array into two non-empty sub-sets such that:
- The elements of the first set are strictly smaller than x.
- The elements of the second set are strictly greater than x.
- The sum of the elements of both the sets is equal.
If such an integer exists then print Yes otherwise print No.
Examples:
Input: arr[] = {1, 2, 2, 5}
Output: Yes
Choose x = 3, after removing all of its occurrences the array becomes arr[] = {1, 2, 2, 5} {1, 2, 2} and {5} are the required sub-sets.Input: arr[] = {2, 1}
Output: No
Approach:
The idea is to first sort the array and for all the numbers lying between 1 to maximum number present in the array, apply binary search and check if on removing all its occurrences from the array, sum of elements present on its left side (which are smaller than it) and sum of elements present on the right side (which are greater than it) is equal.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function that checks if the given// conditions are satisfiedvoid IfExists(int arr[], int n){    // To store the prefix sum    // of the array elements    int sum[n];Â
    // Sort the array    sort(arr, arr + n);Â
    sum[0] = arr[0];Â
    // Compute the prefix sum array    for (int i = 1; i < n; i++)        sum[i] = sum[i - 1] + arr[i];Â
    // Maximum element in the array    int max = arr[n - 1];Â
    // Variable to check if there exists any number    bool flag = false;Â
    for (int i = 1; i <= max; i++) {Â
        // Stores the index of the largest        // number present in the array        // smaller than i        int findex = 0;Â
        // Stores the index of the smallest        // number present in the array        // greater than i        int lindex = 0;Â
        int l = 0;        int r = n - 1;Â
        // Find index of smallest number        // greater than i        while (l <= r) {            int m = (l + r) / 2;Â
            if (arr[m] < i) {                findex = m;                l = m + 1;            }            else                r = m - 1;        }Â
        l = 1;        r = n;        flag = false;Â
        // Find index of smallest number        // greater than i        while (l <= r) {            int m = (r + l) / 2;Â
            if (arr[m] > i) {                lindex = m;                r = m - 1;            }            else                l = m + 1;        }Â
        // If there exists a number        if (sum[findex] == sum[n - 1] - sum[lindex - 1]) {            flag = true;            break;        }    }Â
    // If no such number exists    // print no    if (flag)        cout << "Yes";    else        cout << "No";}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 1, 2, 2, 5 };Â Â Â Â int n = sizeof(arr) / sizeof(int);Â Â Â Â IfExists(arr, n);Â
    return 0;} |
Java
// Java implementation of the approach import java.util.*;Â
class GFG{Â
// Function that checks if the given // conditions are satisfied static void IfExists(int arr[], int n) {     // To store the prefix sum     // of the array elements     int sum[] = new int[n]; Â
    // Sort the array     Arrays.sort(arr); Â
    sum[0] = arr[0]; Â
    // Compute the prefix sum array     for (int i = 1; i < n; i++)         sum[i] = sum[i - 1] + arr[i]; Â
    // Maximum element in the array     int max = arr[n - 1]; Â
    // Variable to check if there exists any number     boolean flag = false; Â
    for (int i = 1; i <= max; i++)     { Â
        // Stores the index of the largest         // number present in the array         // smaller than i         int findex = 0; Â
        // Stores the index of the smallest         // number present in the array         // greater than i         int lindex = 0; Â
        int l = 0;         int r = n - 1; Â
        // Find index of smallest number         // greater than i         while (l <= r)         {             int m = (l + r) / 2; Â
            if (arr[m] < i)             {                 findex = m;                 l = m + 1;             }             else                r = m - 1;         } Â
        l = 1;         r = n;         flag = false; Â
        // Find index of smallest number         // greater than i         while (l <= r)         {             int m = (r + l) / 2; Â
            if (arr[m] > i)             {                 lindex = m;                 r = m - 1;             }             else                l = m + 1;         } Â
        // If there exists a number         if (sum[findex] == sum[n - 1] - sum[lindex - 1])         {             flag = true;             break;         }     } Â
    // If no such number exists     // print no     if (flag)         System.out.println("Yes");     else        System.out.println("No"); } Â
// Driver code public static void main(String args[]){ Â Â Â Â int arr[] = { 1, 2, 2, 5 }; Â Â Â Â int n = arr.length; Â Â Â Â IfExists(arr, n); }} Â
// This code is contributed by Arnab Kundu |
Python3
# Python3 implementation of the approach Â
# Function that checks if the given # conditions are satisfied def IfExists(arr, n) :Â
    # To store the prefix sum     # of the array elements     sum = [0] * n; Â
    # Sort the array     arr.sort(); Â
    sum[0] = arr[0]; Â
    # Compute the prefix sum array     for i in range(1, n) :         sum[i] = sum[i - 1] + arr[i]; Â
    # Maximum element in the array     max = arr[n - 1]; Â
    # Variable to check if there     # exists any number     flag = False; Â
    for i in range(1, max + 1) :Â
        # Stores the index of the largest         # number present in the array         # smaller than i         findex = 0; Â
        # Stores the index of the smallest         # number present in the array         # greater than i         lindex = 0; Â
        l = 0;         r = n - 1; Â
        # Find index of smallest number         # greater than i         while (l <= r) :            m = (l + r) // 2; Â
            if (arr[m] < i) :                findex = m;                 l = m + 1;                          else :                r = m - 1;                  l = 1;         r = n;         flag = False; Â
        # Find index of smallest number         # greater than i         while (l <= r) :             m = (r + l) // 2; Â
            if (arr[m] > i) :                 lindex = m;                 r = m - 1;                          else :                l = m + 1;                  # If there exists a number         if (sum[findex] == sum[n - 1] -                           sum[lindex - 1]) :             flag = True;             break;              # If no such number exists     # print no     if (flag) :         print("Yes");     else :        print("No"); Â
# Driver code if __name__ == "__main__" : Â
    arr = [ 1, 2, 2, 5 ];          n = len(arr) ;    IfExists(arr, n);      # This code is contributed by Ryuga |
C#
// C# implementation of the approach using System;Â
class GFG{     // Function that checks if the given // conditions are satisfied static void IfExists(int[] arr, int n) {     // To store the prefix sum     // of the array elements     int[] sum = new int[n]; Â
    // Sort the array     Array.Sort(arr); Â
    sum[0] = arr[0]; Â
    // Compute the prefix sum array     for (int i = 1; i < n; i++)         sum[i] = sum[i - 1] + arr[i]; Â
    // Maximum element in the array     int max = arr[n - 1]; Â
    // Variable to check if there exists any number     bool flag = false; Â
    for (int i = 1; i <= max; i++)     { Â
        // Stores the index of the largest         // number present in the array         // smaller than i         int findex = 0; Â
        // Stores the index of the smallest         // number present in the array         // greater than i         int lindex = 0; Â
        int l = 0;         int r = n - 1; Â
        // Find index of smallest number         // greater than i         while (l <= r)         {             int m = (l + r) / 2; Â
            if (arr[m] < i)             {                 findex = m;                 l = m + 1;             }             else                r = m - 1;         } Â
        l = 1;         r = n;         flag = false; Â
        // Find index of smallest number         // greater than i         while (l <= r)         {             int m = (r + l) / 2; Â
            if (arr[m] > i)             {                 lindex = m;                 r = m - 1;             }             else                l = m + 1;         } Â
        // If there exists a number         if (sum[findex] == sum[n - 1] - sum[lindex - 1])         {             flag = true;             break;         }     } Â
    // If no such number exists     // print no     if (flag)         Console.WriteLine("Yes");     else        Console.WriteLine("No"); } Â
// Driver code public static void Main(){ Â Â Â Â int[] arr = { 1, 2, 2, 5 }; Â Â Â Â int n = arr.Length; Â Â Â Â IfExists(arr, n); }} Â
// This code is contributed by Code_Mech. |
Javascript
// Java implementation of the approach Â
// Function that checks if the given // conditions are satisfiedfunction ifExists(arr, n) {    // To store the prefix sum     // of the array elements    const sum = new Array(n).fill(0);    // Sort the array     arr.sort((a, b) => a - b);       sum[0] = arr[0];    // Compute the prefix sum array     for (let i = 1; i < n; i++) {      sum[i] = sum[i - 1] + arr[i];    }  // Maximum element in the array     const max = arr[n - 1];         // Variable to check if there exists any number     let flag = false;       for (let i = 1; i <= max; i++) {         // Stores the index of the largest         // number present in the array        // smaller than i       let findex = 0;              // Stores the index of the smallest       // number present in the array       // greater than i      let lindex = 0;             let l = 0;      let r = n - 1;             // Find index of smallest number         // greater than i       while (l <= r) {        const m = Math.floor((l + r) / 2);           if (arr[m] < i) {          findex = m;          l = m + 1;        } else {          r = m - 1;        }      }         l = 1;      r = n;      flag = false;         while (l <= r) {        const m = Math.floor((r + l) / 2);           if (arr[m] > i) {          lindex = m;          r = m - 1;        } else {          l = m + 1;        }      }         if (sum[findex] === sum[n - 1] - sum[lindex - 1]) {        flag = true;        break;      }    }       if (flag) {      console.log("Yes");    } else {      console.log("No");    }}   // Driver code const arr = [1, 2, 2, 5];const n = arr.length;ifExists(arr, n);Â
// This code is contributed by Dwaipayan Bandyopadhyay |
PHP
<?php// PHP implementation of the approachÂ
// Function that checks if the given// conditions are satisfiedfunction IfExists($arr, $n){    // To store the prefix $sum    // of the array elements    $sum = array_fill(0, $n, 0);Â
    // Sort the array    sort($arr);Â
    $sum[0] = $arr[0];Â
    // Compute the prefix sum array    for ($i = 1; $i < $n; $i++)        $sum[$i] = $sum[$i - 1] + $arr[$i];Â
    // Maximum element in the array    $max = $arr[$n - 1];Â
    // Variable to check if there exists any number    $flag = false;Â
    for ($i = 1; $i <= $max; $i++)     {Â
        // Stores the index of the largest        // number present in the array        // smaller than i        $findex = 0;Â
        // Stores the index of the smallest        // number present in the array        // greater than i        $lindex = 0;Â
        $l = 0;        $r = $n - 1;Â
        // Find index of smallest number        // greater than i        while ($l <= $r)         {            $m = ($l + $r) / 2;             if ($arr[$m] < $i)             {                $findex = $m;                $l = $m + 1;            }            else                $r = $m - 1;        }Â
        $l = 1;        $r = $n;        $flag = false;Â
        // Find index of smallest number        // greater than i        while ($l <= $r)        {            $m = ($r + $l) / 2;Â
            if ($arr[$m] > $i)             {                $lindex = $m;                $r = $m - 1;            }            else                $l = $m + 1;        }Â
        // If there exists a number        if ($sum[$findex] == $sum[$n - 1] -                             $sum[$lindex - 1])        {            $flag = true;            break;        }    }Â
    // If no such number exists    // print no    if ($flag == true)        echo "Yes";    else        echo "No";}Â
// Driver code$arr = array(1, 2, 2, 5 );$n = sizeof($arr);IfExists($arr, $n);Â
// This code is contributed by ihritik?> |
Yes
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



