Open In App

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

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: 

Below is the implementation of the above approach: 




// 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 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 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# 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




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

Below is the implementation of the above approach:




// 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;
}




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");
        }
    }
}




# 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")




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");
        }
    }
}




// 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)


Article Tags :