Partition Equal Subset Sum

35 min · canPartition()

A pile of workloads can look balanced by count and still be wildly unbalanced by weight. Here you care about the totals.

Given an array of positive integers nums, return true when you can divide its positions into two groups with the same sum. Return false otherwise.

A partition is a split where every position belongs to exactly one of the two groups. Equal values at different positions still count as separate choices.

A few ground rules:

  • You choose each position at most once.
  • The order of the values doesn't matter.
  • You only return whether an equal split exists; you don't need to return the groups.

Constraints

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

Hints

Check the total first

Two equal integer sums must add to an even total. An odd total lets you answer immediately.

Turn two groups into one target

If the total is T, you only need to ask whether some positions add up to T / 2. Everything you don't choose automatically forms the other group.

Protect the choose-once rule

Keep a boolean table of reachable sums. Process that table from the target down to the current value so one array position can't be reused during its own update.

Follow-up

Could you recover one actual equal partition while keeping the same time complexity?

Visible cases

Examples

Example 1

ready
Input
nums = [
  1,
  5,
  11,
  5
]
Expected
true
Why
[1, 5, 5] and [11] both total 11

Example 2

ready
Input
nums = [
  1,
  2,
  3,
  5
]
Expected
false
Why
the total is odd, so two equal integer sums are impossible

Example 3

ready
Input
nums = [
  1,
  1
]
Expected
true
Why
put one 1 in each group

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite