Given an array containing N elements, each element is either 1 or 2. The task is to find out whether the array can be divided into 2 parts such that the sum of elements in both parts is equal.
Examples:
Input : N = 3, arr[] = {1, 1, 2}
Output : YES
Input : N = 4, arr[] = {1, 2, 2, }
Output : NO
The idea is to observe that the array can be divided into two parts with equal sum only if the overall sum of the array is even, i.e. divisible by 2.
Let’s say the overall sum of the array is denoted by sum.
Now, there arise two cases:Â
- If sum/2 is even: When the value of sum/2 is also even, it means that the sum of each of the two parts is also even and we need not consider anything special. So, return true for this case.
- If sum/2 is odd: When the value of sum/2 is ODD, it means that the sum of each part is also odd. This is only possible when each of the two parts of the array contains at least one 1. Consider the cases when summing = 2 or 6 or 10. So, when sum/2 is odd, check if there is at least one 1 in the array.
Below is the implementation of the above approach:Â
C++
// C++ implementation of the above // approach: Â
#include <bits/stdc++.h> using namespace std; Â
// Function to check if it is possible to // split the array in two parts with // equal sum bool isSpiltPossible( int n, int a[]) { Â Â Â Â int sum = 0, c1 = 0; Â
    // Calculate sum of elements     // and count of 1's     for ( int i = 0; i < n; i++) {         sum += a[i]; Â
        if (a[i] == 1) {             c1++;         }     } Â
    // If total sum is odd, return False     if (sum % 2)         return false ; Â
    // If sum of each part is even,     // return True     if ((sum / 2) % 2 == 0)         return true ; Â
    // If sum of each part is even but     // there is atleast one 1     if (c1 > 0)         return true ;     else         return false ; } Â
// Driver Code int main() { Â Â Â Â int n = 3; Â Â Â Â int a[] = { 1, 1, 2 }; Â
    if (isSpiltPossible(n, a))         cout << "YES" ;     else         cout << "NO" ; Â
    return 0; } |
Java
// Java implementation of the above // approach: class GFG { Â Â Â Â Â // Function to check if it is possible // to split the array in two parts with // equal sum static boolean isSpiltPossible( int n, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int a[]) { Â Â Â Â int sum = 0 , c1 = 0 ; Â
    // Calculate sum of elements     // and count of 1's     for ( int i = 0 ; i < n; i++)     {         sum += a[i]; Â
        if (a[i] == 1 )         {             c1++;         }     } Â
    // If total sum is odd, return False     if (sum % 2 != 0 )         return false ; Â
    // If sum of each part is even,     // return True     if ((sum / 2 ) % 2 == 0 )         return true ; Â
    // If sum of each part is even but     // there is atleast one 1     if (c1 > 0 )         return true ;     else         return false ; } Â
// Driver Code public static void main(String[] args) { Â Â Â Â int n = 3 ; Â Â Â Â int a[] = { 1 , 1 , 2 }; Â
    if (isSpiltPossible(n, a))         System.out.println( "YES" );     else         System.out.println( "NO" ); } } Â
// This code is contributed by // Code Mech |
Python3
# Python3 implementation of the above # approach: Â
# Function to check if it is possible # to split the array in two halfs with # equal Sum def isSpiltPossible(n, a): Â
    Sum = 0     c1 = 0 Â
    # Calculate Sum of elements     # and count of 1's     for i in range (n):         Sum + = a[i] Â
        if (a[i] = = 1 ):             c1 + = 1 Â
    # If total Sum is odd, return False     if ( Sum % 2 ):         return False Â
    # If Sum of each half is even,     # return True     if (( Sum / / 2 ) % 2 = = 0 ):         return True Â
    # If Sum of each half is even     # but there is atleast one 1     if (c1 > 0 ):         return True     else :         return False Â
# Driver Code n = 3 a = [ 1 , 1 , 2 ] Â
if (isSpiltPossible(n, a)): Â Â Â Â print ( "YES" ) else : Â Â Â Â print ( "NO" ) Â
# This code is contributed # by Mohit Kumar |
C#
// C# implementation of the above // approach: using System; Â
class GFG { Â Â Â Â Â // Function to check if it is possible // to split the array in two parts with // equal sum static bool isSpiltPossible( int n, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int [] a) { Â Â Â Â int sum = 0, c1 = 0; Â
    // Calculate sum of elements     // and count of 1's     for ( int i = 0; i < n; i++)     {         sum += a[i]; Â
        if (a[i] == 1)         {             c1++;         }     } Â
    // If total sum is odd, return False     if (sum % 2 != 0)         return false ; Â
    // If sum of each part is even,     // return True     if ((sum / 2) % 2 == 0)         return true ; Â
    // If sum of each part is even but     // there is atleast one 1     if (c1 > 0)         return true ;     else         return false ; } Â
// Driver Code public static void Main() { Â Â Â Â int n = 3; Â Â Â Â int [] a = { 1, 1, 2 }; Â
    if (isSpiltPossible(n, a))         Console.WriteLine( "YES" );     else         Console.WriteLine( "NO" ); } } Â
// This code is contributed by // Code Mech |
Javascript
<script> Â
// Javascript implementation of the above approach Â
// Function to check if it is possible // to split the array in two parts with // equal sum function isSpiltPossible(n, a) { Â Â Â Â let sum = 0, c1 = 0; Â
    // Calculate sum of elements     // and count of 1's     for (let i = 0; i < n; i++)     {         sum += a[i]; Â
        if (a[i] == 1)         {             c1++;         }     } Â
    // If total sum is odd, return False     if (sum % 2 != 0)         return false ; Â
    // If sum of each part is even,     // return True     if ((sum / 2) % 2 == 0)         return true ; Â
    // If sum of each part is even but     // there is atleast one 1     if (c1 > 0)         return true ;     else         return false ; } Â
// driver program              let n = 3;     let a = [ 1, 1, 2 ]; Â
    if (isSpiltPossible(n, a))         document.write( "YES" );     else         document.write( "NO" );    </script> |
PHP
<?php // PHP implementation of the above // approach: Â
// Function to check if it is possible // to split the array in two parts with // equal sum function isSpiltPossible( $n , $a ) { Â Â Â Â $sum = 0; $c1 = 0; Â
    // Calculate sum of elements     // and count of 1's     for ( $i = 0; $i < $n ; $i ++)     {         $sum += $a [ $i ]; Â
        if ( $a [ $i ] == 1)         {             $c1 ++;         }     } Â
    // If total sum is odd, return False     if ( $sum % 2 != 0)         return false; Â
    // If sum of each part is even,     // return True     if (( $sum / 2) % 2 == 0)         return true; Â
    // If sum of each part is even but     // there is atleast one 1     if ( $c1 > 0)         return true;     else         return false; } Â
// Driver Code $n = 3; $a = array ( 1, 1, 2 ); Â
if (isSpiltPossible( $n , $a ))     echo ( "YES" ); else     echo ( "NO" ); Â
// This code is contributed by // Code Mech ?> |
YES
Time Complexity: O(N), since there runs a loop from 0 to (n – 1).
 Auxiliary Space: O(1), since no extra space has been taken.
Approach 2: Dynamic Programming: Here is a dynamic programming approach to solve the problem of splitting an array into two parts with equal sum:
- Calculate the sum of all elements in the array.
- If the sum is odd, then it is not possible to split the array into two parts with equal sum. Return False.
- If the sum is even, then find if there exists a subset of the array whose sum is equal to half of the total sum. If such a subset exists, then the array can be split into two parts with equal sum. Otherwise, it is not possible. This can be done by dynamic programming to find such a subset using the following steps:
- Create a boolean 2D array dp[n+1][sum+1], where dp[i][j] represents whether it is possible to obtain a sum of j using the first i elements of the array.
- Initialize dp[0][0] to true, since it is always possible to obtain a sum of 0 using 0 elements.
- For each element a[i] in the array, iterate over all possible sums from 0 to sum/2, and update dp[i][j] as follows:
- If j < a[i], then dp[i][j] = dp[i-1][j], since we cannot include a[i] in the subset if it is greater than the current sum j. Otherwise, dp[i][j] = dp[i-1][j] || dp[i-1][j-a[i]], since we can either exclude or include a[i] in the subset.
- If dp[n][sum/2] is true, then it is possible to split the array into two parts with equal sum. Otherwise, it is not possible.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to check if it is possible to // split the array or not bool isSpiltPossible( int n, int a[]) { Â Â Â Â int sum = 0; Â
    // Find the sum of array elements     for ( int i = 0; i < n; i++) {         sum += a[i];     } Â
    // Not Possible Scenario     if (sum % 2 != 0) {         return false ;     }     int half_sum = sum / 2; Â
    bool dp[n + 1][half_sum + 1]; Â
    // Dynamic Programming Approach     for ( int i = 0; i <= n; i++) {         dp[i][0] = true ;     }     for ( int i = 1; i <= half_sum; i++) {         dp[0][i] = false ;     }     for ( int i = 1; i <= n; i++) {         for ( int j = 1; j <= half_sum; j++) { Â
            // Conditions to update the dp array             if (j < a[i - 1]) {                 dp[i][j] = dp[i - 1][j];             }             else {                 dp[i][j] = dp[i - 1][j]                            || dp[i - 1][j - a[i - 1]];             }         }     }     return dp[n][half_sum]; } Â
// Driver Code int main() { Â Â Â Â int arr[] = { 1, 1, 2 }; Â Â Â Â int N = sizeof (arr) / sizeof (arr[0]); Â
    if (isSpiltPossible(N, arr)) {         cout << "YES" ;     }     else {         cout << "NO" ;     }     return 0; } |
Java
import java.util.*; Â
public class Main { Â Â Â Â public static boolean isSplitPossible( int n, int [] a) { Â Â Â Â Â Â Â Â int sum = 0 ; Â
        // Find the sum of array elements         for ( int i = 0 ; i < n; i++) {             sum += a[i];         } Â
        // Not Possible Scenario         if (sum % 2 != 0 ) {             return false ;         }         int half_sum = sum / 2 ; Â
        boolean [][] dp = new boolean [n + 1 ][half_sum + 1 ]; Â
        // Dynamic Programming Approach         for ( int i = 0 ; i <= n; i++) {             dp[i][ 0 ] = true ;         }         for ( int i = 1 ; i <= half_sum; i++) {             dp[ 0 ][i] = false ;         }         for ( int i = 1 ; i <= n; i++) {             for ( int j = 1 ; j <= half_sum; j++) { Â
                // Conditions to update the dp array                 if (j < a[i - 1 ]) {                     dp[i][j] = dp[i - 1 ][j];                 } else {                     dp[i][j] = dp[i - 1 ][j] || dp[i - 1 ][j - a[i - 1 ]];                 }             }         }         return dp[n][half_sum];     } Â
    public static void main(String[] args) {         int [] arr = { 1 , 1 , 2 };         int N = arr.length; Â
        if (isSplitPossible(N, arr)) {             System.out.println( "YES" );         } else {             System.out.println( "NO" );         }     } } |
Python3
# Function to check if it is possible to # split the array or not def isSpiltPossible(n, a):     # Find the sum of array elements     sum = 0     for i in range (n):         sum + = a[i]          # Not Possible Scenario     if sum % 2 ! = 0 :         return False     half_sum = sum / / 2          dp = [[ False for j in range (half_sum + 1 )] for i in range (n + 1 )] Â
    # Dynamic Programming Approach     for i in range (n + 1 ):         dp[i][ 0 ] = True     for i in range ( 1 , half_sum + 1 ):         dp[ 0 ][i] = False     for i in range ( 1 , n + 1 ):         for j in range ( 1 , half_sum + 1 ): Â
            # Conditions to update the dp array             if j < a[i - 1 ]:                 dp[i][j] = dp[i - 1 ][j]             else :                 dp[i][j] = dp[i - 1 ][j] or dp[i - 1 ][j - a[i - 1 ]]          return dp[n][half_sum] Â
# Driver Code arr = [ 1 , 1 , 2 ] N = len (arr) Â
if isSpiltPossible(N, arr): Â Â Â Â print ( "YES" ) else : Â Â Â Â print ( "NO" ) |
C#
using System; Â
public class SplitArray {     // Function to check if it is possible to split the array or not     public static bool IsSplitPossible( int n, int [] arr)     {         int sum = 0; Â
        // Find the sum of array elements         for ( int i = 0; i < n; i++)         {             sum += arr[i];         } Â
        // Not Possible Scenario         if (sum % 2 != 0)         {             return false ;         } Â
        int halfSum = sum / 2; Â
        bool [,] dp = new bool [n + 1, halfSum + 1]; Â
        // Dynamic Programming Approach         for ( int i = 0; i <= n; i++)         {             dp[i, 0] = true ;         } Â
        for ( int i = 1; i <= halfSum; i++)         {             dp[0, i] = false ;         } Â
        for ( int i = 1; i <= n; i++)         {             for ( int j = 1; j <= halfSum; j++)             {                 // Conditions to update the dp array                 if (j < arr[i - 1])                 {                     dp[i, j] = dp[i - 1, j];                 }                 else                 {                     dp[i, j] = dp[i - 1, j] || dp[i - 1, j - arr[i - 1]];                 }             }         } Â
        return dp[n, halfSum];     } Â
    // Driver Code     public static void Main( string [] args)     {         int [] arr = { 1, 1, 2 };         int n = arr.Length; Â
        if (IsSplitPossible(n, arr))         {             Console.WriteLine( "YES" );         }         else         {             Console.WriteLine( "NO" );         }     } } |
Javascript
// Function to check if it is possible to // split the array or not function isSplitPossible(n, a) { Â Â Â Â let sum = 0; Â
    // Find the sum of array elements     for (let i = 0; i < n; i++) {         sum += a[i];     } Â
    // Not Possible Scenario     if (sum % 2 !== 0) {         return false ;     } Â
    const halfSum = sum / 2; Â
    // Dynamic Programming Approach     const dp = Array.from({         length: n + 1     }, () => Array(halfSum + 1)); Â
    for (let i = 0; i <= n; i++) {         dp[i][0] = true ;     } Â
    for (let i = 1; i <= halfSum; i++) {         dp[0][i] = false ;     } Â
    for (let i = 1; i <= n; i++) {         for (let j = 1; j <= halfSum; j++) {             // Conditions to update the dp array             if (j < a[i - 1]) {                 dp[i][j] = dp[i - 1][j];             } else {                 dp[i][j] = dp[i - 1][j] || dp[i - 1][j - a[i - 1]];             }         }     } Â
    return dp[n][halfSum]; } Â
// Driver Code const arr = [1, 1, 2]; const N = arr.length; Â
if (isSplitPossible(N, arr)) { Â Â Â Â console.log( "YES" ); } else { Â Â Â Â console.log( "NO" ); } // sinudp5vi |
YES
Time Complexity: O(n*sum), where n is the size of the array and sum is the sum of all elements in the array.
Space complexity: O(sum/2)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!