Partition Equal Subset Sum — LeetCode 416 Python Solution

MediumArrayDynamic Programming
Problem
#416
Reading time
2 min

The problem

Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.

Example

Input
nums = [1,5,11,5]
Output
true
Explanation
The array can be partitioned as [1, 5, 5] and [11].

Python solution

Python
class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        m, mod = divmod(sum(nums), 2)
        if mod:
            return False
        n = len(nums)
        f = [[False] * (m + 1) for _ in range(n + 1)]
        f[0][0] = True
        for i, x in enumerate(nums, 1):
            for j in range(m + 1):
                f[i][j] = f[i - 1][j] or (j >= x and f[i - 1][j - x])
        return f[n][m]

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 416. Partition Equal Subset Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and Grind 75.

Frequently asked questions

How hard is LeetCode 416. Partition Equal Subset Sum?
LeetCode 416. Partition Equal Subset Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 416. Partition Equal Subset Sum?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 416. Partition Equal Subset Sum?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 416. Partition Equal Subset Sum cover?
LeetCode 416. Partition Equal Subset Sum is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview