Subset sum equals to target

Dynamic Programming DP on subsequences Hard
  • This programming problem is often used in financial software or apps where it's crucial to match transactions or set of numbers to specific totals—in fraud check algorithms, for instance, or split payments
  • It's also known as the subset-sum problem and is a common example of the 'knapsack problem' which has various applications in cryptography, complexity theory, and computer networks

Given an array arr of n integers and an integer target, determine if there is a subset of the given array with a sum equal to the given target.

Examples:

Input: arr = [1, 2, 7, 3], target = 6

Output: True

Explanation: There is a subset (1, 2, 3) with sum 6.

Input: arr = [2, 3, 5], target = 6

Output: False

Explanation: There is no subset with sum 6.

Input: arr = [7, 54, 4, 12, 15, 5], target = 9

Constraints

  • 1 <= n = 100
  • 1<= arr[i] <= 100
  • 1<= target <= 5*103

Hints

  • "A DP approach optimally solves this problem using a boolean DP table (dp[i][j]), where: dp[i][j] represents whether a subset of the first i elements has a sum equal to j."
  • "If we exclude arr[i], the result depends on dp[i-1][j]. If we include arr[i], the result depends on dp[i-1][j - arr[i]]. If either case is True, then dp[i][j] = True. Thus, the recurrence relation is: dp[i][j] = dp[i-1][j] OR dp[i-1][j - arr[i]] (if j >= arr[i])."
  • "Instead of a dp[n][target] table, we can use a single 1D array (dp[target]), updating from right to left to avoid overwriting values. dp[j] = dp[j] OR dp[j - arr[i]]"

Company Tags

Uber Ernst & Young Intel Bloomberg PayPal Stripe Teladoc Health Roblox IBM Epic Systems Twilio OYO Rooms Western Digital Bungie Roche Visa Wayfair Rockstar Games Goldman Sachs ARM Snowflake Square Airbnb Broadcom Medtronic Google Microsoft Amazon Meta Apple Netflix Adobe