You are given an array/list ‘ARR’ of ‘N’ positive integers and an integer ‘K’. Your task is to check if there exists a subset in ‘ARR’ with a sum equal to ‘K’.
Note: Return true if there exists a subset with sum equal to ‘K’. Otherwise, return false.
For Example :
If ‘ARR’ is {1,2,3,4} and ‘K’ = 4, then there exists 2 subsets with sum = 4. These are {1,3} and {4}. Hence, return true.
Input Format :
The first line contains a single integer T representing the number of test cases.
The first line of each test case contains two space-separated integers ‘N’ and ‘K’ representing the size of the input ‘ARR’ and the required sum as discussed above.
The next line of each test case contains ‘N’ single space-separated integers that represent the elements of the ‘ARR’.
Output Format :
For each test case, return true or false as discussed above.
Output for each test case will be printed in a separate line.
Note:
You don’t need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 10^3
0 <= ARR[i] <= 10^9
0 <= K <= 10^9
Time Limit: 1 sec
The brute force approach is to use recursion. Generate all subsets and count the number of subsets with sum as 0. The time complexity of this approach would be exponential (2^n).
Dynamic programming ca...read more
The idea is to generate all possible subsets and check if any of them sums up to ‘K’. This can be done through recursion.
Here is the algorithm:
subsetSumToK(N , K , ARR):
- Initialize integer v...read more
The idea is to generate all possible subsets and check if any of them sums up to ‘K’. Along with that, we will use memoization to store previously calculated results to avoid repetition and...read more
The idea is to use dynamic programming to generate all the possible subsets and check if these subsets sum up to ‘K’.
Here is the algorithm:
- Create a boolean 2D array/list ‘DP’ of s...read more
Top PayPal Software Developer interview questions & answers
Popular interview questions of Software Developer
Reviews
Interviews
Salaries
Users/Month