Arena / Problems /

416. Partition Equal Subset Sum

Medium 0/10 Thrones Claimed
Prev Next

Problem Specification

LeetCode #416

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 1
Input: nums = [1,5,11,5]
Output: true
Explanation:

The array can be partitioned as [1, 5, 5] and [11].

Example 2
Input: nums = [1,2,3,5]
Output: false
Explanation:

The array cannot be partitioned into equal sum subsets.

Constraints
  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100
⚔️

Vacant Python Throne

No developer has claimed the Python throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • When we first see this problem, we might want to loop through all subsets of the array. If there is a subset whose sum is equal to half of the sum, then return true. This can be achieved with a backtracking algorithm, but after seeing the constraint nums.length <= 200, we can estimate that the program will time out.
  • This problem can be solved using the 0/1 knapsack problem algorithm.
class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        sum_ = sum(nums)

        if sum_ % 2 == 1:
            return False

        dp = [False] * ((sum_ // 2) + 1)
        dp[0] = True

        for num in nums:
            # If not traversing in reverse order, the newly assigned value `dp[j]` will act as `dp[j - num]` later,
            # then the subsequent `dp[j]` will be affected. But each `num` can only be used once!
            j = len(dp) - 1
            while j >= num:
                dp[j] = dp[j] or dp[j - num]
                j -= 1

        return dp[-1]
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        sum_ = sum(nums)

        if sum_ % 2 == 1:
            return False

        dp = [False] * ((sum_ // 2) + 1)
        dp[0] = True

        for num in nums:
            # Make a copy of the 'dp' that has not been modified to eliminate distractions.
            dc = dp.copy()

            for j in range(num, len(dp)): # any order is fine
                dp[j] = dc[j] or dc[j - num] # Use 'dc' instead of 'dp' because 'dp' will be modified.

        return dp[-1]
⚔️

Vacant C# Throne

No developer has claimed the C# throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • When we first see this problem, we might want to loop through all subsets of the array. If there is a subset whose sum is equal to half of the sum, then return true. This can be achieved with a backtracking algorithm, but after seeing the constraint nums.length <= 200, we can estimate that the program will time out.
  • This problem can be solved using the 0/1 knapsack problem algorithm.
public class Solution
{
    public bool CanPartition(int[] nums)
    {
        int sum = nums.Sum();

        if (sum % 2 == 1)
            return false;

        var dp = new bool[sum / 2 + 1];
        dp[0] = true;

        foreach (var num in nums)
        {
            for (var j = dp.GetUpperBound(0); j >= num; j--)
            {
                dp[j] = dp[j] || dp[j - num];
            }
        }

        return dp.Last();
    }
}
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

public class Solution
{
    public bool CanPartition(int[] nums)
    {
        int sum = nums.Sum();

        if (sum % 2 == 1)
            return false;

        var dp = new bool[sum / 2 + 1];
        dp[0] = true;

        foreach (var num in nums)
        {
            var dc = (bool[])dp.Clone();

            for (var j = num; j < dp.Length; j++)
            {
                dp[j] = dc[j] || dc[j - num];
            }
        }

        return dp.Last();
    }
}
⚔️

Vacant C++ Throne

No developer has claimed the C++ throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • When we first see this problem, we might want to loop through all subsets of the array. If there is a subset whose sum is equal to half of the sum, then return true. This can be achieved with a backtracking algorithm, but after seeing the constraint nums.length <= 200, we can estimate that the program will time out.
  • This problem can be solved using the 0/1 knapsack problem algorithm.
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        auto sum = reduce(nums.begin(), nums.end());

        if (sum % 2 == 1) {
            return false;
        }

        auto dp = vector<bool>(sum / 2 + 1);
        dp[0] = true;

        for (auto num : nums) {
            for (auto j = dp.size() - 1; j >= num; j--) {
                dp[j] = dp[j] || dp[j - num];
            }
        }

        return dp.back();
    }
};
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

class Solution {
public:
    bool canPartition(vector<int>& nums) {
        auto sum = reduce(nums.begin(), nums.end());

        if (sum % 2 == 1) {
            return false;
        }

        auto dp = vector<bool>(sum / 2 + 1);
        dp[0] = true;

        for (auto num : nums) {
            auto dc = dp;

            for (auto j = num; j < dp.size(); j++) {
                dp[j] = dc[j] || dc[j - num];
            }
        }

        return dp.back();
    }
};
⚔️

Vacant Java Throne

No developer has claimed the Java throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • When we first see this problem, we might want to loop through all subsets of the array. If there is a subset whose sum is equal to half of the sum, then return true. This can be achieved with a backtracking algorithm, but after seeing the constraint nums.length <= 200, we can estimate that the program will time out.
  • This problem can be solved using the 0/1 knapsack problem algorithm.
class Solution {
    public boolean canPartition(int[] nums) {
        var sum = IntStream.of(nums).sum();

        if (sum % 2 == 1) {
            return false;
        }

        var dp = new boolean[sum / 2 + 1];
        dp[0] = true;

        for (var num : nums) {
            for (var j = dp.length - 1; j >= num; j--) {
                dp[j] = dp[j] || dp[j - num];
            }
        }

        return dp[dp.length - 1];
    }
}
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

class Solution {
    public boolean canPartition(int[] nums) {
        var sum = IntStream.of(nums).sum();

        if (sum % 2 == 1) {
            return false;
        }

        var dp = new boolean[sum / 2 + 1];
        dp[0] = true;

        for (var num : nums) {
            var dc = dp.clone();

            for (var j = num; j < dp.length; j++) {
                dp[j] = dc[j] || dc[j - num];
            }
        }

        return dp[dp.length - 1];
    }
}
⚔️

Vacant Javascript Throne

No developer has claimed the Javascript throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • When we first see this problem, we might want to loop through all subsets of the array. If there is a subset whose sum is equal to half of the sum, then return true. This can be achieved with a backtracking algorithm, but after seeing the constraint nums.length <= 200, we can estimate that the program will time out.
  • This problem can be solved using the 0/1 knapsack problem algorithm.
var canPartition = function (nums) {
  const sum = _.sum(nums)

  if (sum % 2 == 1) {
    return false
  }

  const dp = Array(sum / 2 + 1).fill(false)
  dp[0] = true

  for (const num of nums) {
    for (let j = dp.length - 1; j >= num; j--) {
      dp[j] = dp[j] || dp[j - num]
    }
  }

  return dp.at(-1)
};
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

var canPartition = function (nums) {
  const sum = _.sum(nums)

  if (sum % 2 == 1) {
    return false
  }

  const dp = Array(sum / 2 + 1).fill(false)
  dp[0] = true

  for (const num of nums) {
    const dc = [...dp]

    for (let j = num; j < dp.length; j++) {
      dp[j] = dc[j] || dc[j - num]
    }
  }

  return dp.at(-1)
};
⚔️

Vacant Go Throne

No developer has claimed the Go throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • When we first see this problem, we might want to loop through all subsets of the array. If there is a subset whose sum is equal to half of the sum, then return true. This can be achieved with a backtracking algorithm, but after seeing the constraint nums.length <= 200, we can estimate that the program will time out.
  • This problem can be solved using the 0/1 knapsack problem algorithm.
func canPartition(nums []int) bool {
    sum := 0
    for _, num := range nums {
        sum += num
    }

    if sum % 2 == 1 {
        return false
    }

    dp := make([]bool, sum / 2 + 1)
    dp[0] = true

    for _, num := range nums {
        for j := len(dp) - 1; j >= num; j-- {
            dp[j] = dp[j] || dp[j - num]
        }
    }

    return dp[len(dp) - 1]
}
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

func canPartition(nums []int) bool {
    sum := 0
    for _, num := range nums {
        sum += num
    }

    if sum % 2 == 1 {
        return false
    }

    dp := make([]bool, sum / 2 + 1)
    dp[0] = true

    for _, num := range nums {
        dc := slices.Clone(dp)

        for j := num; j < len(dp); j++ {
            dp[j] = dc[j] || dc[j - num]
        }
    }

    return dp[len(dp) - 1]
}
⚔️

Vacant Ruby Throne

No developer has claimed the Ruby throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • When we first see this problem, we might want to loop through all subsets of the array. If there is a subset whose sum is equal to half of the sum, then return true. This can be achieved with a backtracking algorithm, but after seeing the constraint nums.length <= 200, we can estimate that the program will time out.
  • This problem can be solved using the 0/1 knapsack problem algorithm.
def can_partition(nums)
  sum = nums.sum

  return false if sum % 2 == 1

  dp = Array.new(sum / 2 + 1, false)
  dp[0] = true

  nums.each do |num|
    (num...dp.size).reverse_each do |j|
      dp[j] = dp[j] || dp[j - num]
    end
  end

  dp[-1]
end
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

def can_partition(nums)
  sum = nums.sum

  return false if sum % 2 == 1

  dp = Array.new(sum / 2 + 1, false)
  dp[0] = true

  nums.each do |num|
    dc = dp.clone

    (num...dp.size).each do |j|
      dp[j] = dc[j] || dc[j - num]
    end
  end

  dp[-1]
end
⚔️

Vacant Rust Throne

No developer has claimed the Rust throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Swift Throne

No developer has claimed the Swift throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Kotlin Throne

No developer has claimed the Kotlin throne for LeetCode #416 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.