Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

Subset Sum Editorial

DSA Editorial, Solution and Code

Practice Problem Link: https://workat.tech/problem-solving/practice/subset-sum

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

Given an array of integers A and a target value target. Find whether there exists a subset in the array A where their sum is equal to target.

Naive Approach

This problem can be solved by a brute force recursion. Notice, that when processing a subset, we have 2 choices, either take the current element or don’t take it. So, we can recursively check for the possibilities and return true if we find an appropriate subset, else return false.

Analysis

  • Time Complexity: Exponential
  • Space Complexity: O(1)

Implementation

C++
int checkSum(vector<int> &A, int n, int target) {
	if(target == 0) {
		return 1;
	}
	if(n == 0) {
		return 0;
	}
	if(A[n - 1] > target) {
		return checkSum(A, n - 1, target);
	}
	return checkSum(A, n - 1, target) || checkSum(A, n - 1, target - A[n - 1]);
}
bool hasValidSubset(vector<int>A, int target) {
    return checkSum(A, A.size(), target);
}
Java
class Solution {
	boolean checkSum(int[] A, int n, int target) {
		if(target == 0) {
			return true;
		}
		if(n == 0) {
			return false;
		}
		if(A[n - 1] > target) {
			return checkSum(A, n - 1, target);
		}
		return checkSum(A, n - 1, target) || checkSum(A, n - 1, target - A[n - 1]);
	}
	boolean hasValidSubset(int[] A, int target) {
	    return checkSum(A, A.length, target);
	}
}

Optimal Approach

We can observe that in our naive approach, multiple recursion calls are the same and are being redundantly recalculated. So, we can memoize those recursive calls using Dynamic Programming, to optimize our time complexity. DP[i][j] will represent if it is possible to attain a subset made of the 1st i elements in the array, which adds up to sum j.

Analysis

  • Time Complexity: O(n * target)
  • Space Complexity: O(n * target)

Implementation

C++
vector<vector<int>> dp;
int checkSum(vector<int> &A, int n, int target) {
	if(target == 0) {
		return 1;
	}
	if(n == 0) {
		return 0;
	}
	if(dp[n][target] != -1){
		return dp[n][target];
	}
	if(A[n - 1] > target) {
		return dp[n][target] = checkSum(A, n - 1, target);
	}
	return dp[n][target] = checkSum(A, n - 1, target) || checkSum(A, n - 1, target - A[n - 1]);
}
bool hasValidSubset(vector<int>A, int target) {
    vector<vector<int>> temp(A.size() + 1, vector<int> (target + 1, -1));
	dp = temp;
    return checkSum(A, A.size(), target);
}
Java
class Solution {
	Boolean dp[][];
	boolean checkSum(int[] A, int n, int target) {
		if(target == 0) {
			return true;
		}
		if(n == 0) {
			return false;
		}
		if(dp[n][target] != null) {
			return dp[n][target];
		}
		if(A[n - 1] > target) {
			dp[n][target] = checkSum(A, n - 1, target);
			return dp[n][target];
		}
		dp[n][target] = (checkSum(A, n - 1, target) || checkSum(A, n - 1, target - A[n - 1]));
		return (dp[n][target]);
	}
	boolean hasValidSubset(int[] A, int target) {
	    dp = new Boolean[A.length + 1][target + 1];
	    return checkSum(A, A.length, target);
	}
}

Bottom-Up Implementation

C++
bool hasValidSubset(vector<int> A, int target) {
	int n = A.size();
	bool dp[n + 1][target + 1];
	for(int i = 0; i <= n; i++) {
		for(int j = 0; j <= target; j++) {
			if(i == 0 && j != 0) {
				dp[i][j] = false;
			}
			else if(j == 0) {
				dp[i][j] = true;
			}
			else {
				if(j - A[i - 1] >= 0) {
					dp[i][j] = dp[i - 1][j - A[i - 1]] || dp[i - 1][j];
				}
				else {
					dp[i][j] = dp[i - 1][j];
				}
			}
		}
	}
    return dp[n][target];
}
Java
class Solution {
	boolean hasValidSubset(int[] A, int target) {
		boolean[][] dp = new boolean[A.length + 1][target + 1];
		for(int i = 0; i <= A.length; i++) {
			for(int j = 0; j <= target; j++) {
				if(j == 0) {
					dp[i][j] = true;
				}
				else if(i == 0) {
					dp[i][j] = false;
				}
				else {
					if(j - A[i - 1] >= 0) {
						dp[i][j] = dp[i - 1][j - A[i - 1]] || dp[i - 1][j];
					}
					else {
						dp[i][j] = dp[i - 1][j];
					}
				}
			}
		}
	    return dp[A.length][target];
	}
}
Related Content
Best Time to Buy and Sell Stocks
Best Time to Buy and Sell Stocks II
Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock IV
Climbing Stairs
Coin Change
Collect Jewels
Combination Sum 1
Combination Sum 2
Combinations
Consecutively Descending Integers
Decode Ways
Edit Distance (Levenshtein Distance)
Minimum Egg Drops
Generate Parentheses
Kth Permutation Sequence
Letter Combinations of a Phone Number
Longest Common Subsequence (LCS)
Longest Increasing Subsequence (LIS)
Longest Palindromic Substring (LPS)
Maximum path sum in matrix
Maximum Product Subarray
Maximum Sum Increasing Subsequence
N Queens Problem
Palindrome Partitioning
Palindrome Partitioning
Palindrome Partitioning 2
Rat In A Maze
Regular Expression Matching
Restore IP Addresses
Rod Cutting
String Permutations
Subset Sum 2
Subsets
Subsets - II
Sudoku Solver
Trapping Rain Water
Tug of War
Unique Paths
Wildcard Matching
Word Break
Word Break
Word Break - II
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet