Open In App

Check if an array of 1s and 2s can be divided into 2 parts with equal sum

Last Updated : 31 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
?>


Output

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


Output

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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads