Subset Sum Equal To K
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
CodingNinjas
author
2y
Recursion
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
CodingNinjas
author
2y
Memoization
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
CodingNinjas
author
2y
Dynamic Programming
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
Add answer anonymously...
Top Siemens Deep Learning Research Intern interview questions & answers
>
Siemens Deep Learning Research Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app