Partition equal subset sum

Dynamic Programming DP on subsequences Hard

Given an array arr of n integers, return true if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal else return false.

Examples:

Input: arr = [1, 10, 21, 10]

Output: True

Explanation: The array can be partitioned as [1, 10, 10] and [21].

Input: arr = [1, 2, 3, 5]

Output: False

Explanation: The array cannot be partitioned into equal sum subsets.

Input: arr = [2, 2, 1, 1]

Constraints

  • 1 ≤ n ≤ 100
  • 1 ≤ arr[i] ≤ 1000
  • n*sum of elements ≤ 105

Hints

  • "Define dp[i][j] where: dp[i][j] → True if there exists a subset of the first i elements whose sum is j. Recurrence Relation: dp[i][j] = dp[i-1][j] OR dp[i-1][j - arr[i]] (if j >= arr[i])"
  • "Since the DP table only depends on the previous row, we can use a 1D array (dp[target]) updated from right to left: dp[j] = dp[j] OR dp[j - arr[i]] (processed in reverse order to prevent overwriting)."

Company Tags

JPMorgan Chase Intel Dropbox Snowflake HashiCorp Unity Technologies Wayfair Medtronic Roblox Teladoc Health OYO Rooms Epic Games Stripe Instacart Texas Instruments eBay AMD Goldman Sachs Riot Games Cloudflare Rakuten Optum Databricks Seagate Technology Broadcom Google Microsoft Amazon Meta Apple Netflix Adobe