Program to check whether we can make group of two partitions with equal sum or not in Python?

Suppose we have a list of numbers called nums, we have to check whether we can partition nums into two groups where the sum of the elements in both groups are the same.

So, if the input is like nums = [2, 3, 6, 5], then the output will be True, as we can make groups like: [2, 6] and [3, 5].

Algorithm

To solve this, we will follow these steps ?

  • total := sum of all elements in nums

  • if total is odd, then

    • return False

  • half := integer part of total / 2

  • dp := a list of size half + 1 and fill with False

  • dp[0] := True

  • for each num in nums, do

    • for i in range half to 0, decrease by 1, do

      • if i >= num, then

        • dp[i] := dp[i] OR dp[i - num]

  • return dp[half]

Example

Let's implement this algorithm to check if we can partition the list into two equal sum groups ?

class Solution:
    def solve(self, nums):
        total = sum(nums)
        
        if total & 1:
            return False
        
        half = total // 2
        
        dp = [True] + [False] * half
        for num in nums:
            for i in range(half, 0, -1):
                if i >= num:
                    dp[i] |= dp[i - num]
        
        return dp[half]

ob = Solution()
nums = [2, 3, 6, 5]
print(ob.solve(nums))

The output of the above code is ?

True

How It Works

This algorithm uses dynamic programming to solve the partition problem. First, we calculate the total sum and check if it's even (if odd, equal partition is impossible). Then we use a boolean array dp where dp[i] represents whether we can achieve sum i using the numbers processed so far. We iterate through each number and update the DP array backwards to avoid using the same number twice.

Example with Another Input

Let's test with a case where equal partition is not possible ?

ob = Solution()
nums = [1, 5, 11, 5]
print(f"Can partition {nums}: {ob.solve(nums)}")

nums2 = [1, 2, 3, 5]
print(f"Can partition {nums2}: {ob.solve(nums2)}")

The output of the above code is ?

Can partition [1, 5, 11, 5]: True
Can partition [1, 2, 3, 5]: False

Conclusion

This dynamic programming approach efficiently determines if a list can be partitioned into two equal sum groups. The algorithm has O(n × sum) time complexity and works by checking if we can achieve exactly half of the total sum using available numbers.

Updated on: 2026-03-25T12:15:11+05:30

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements