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

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

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):

  1. 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:

  1. Create a boolean 2D array/list ‘DP’ of s...read more
Add answer anonymously...
PayPal Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter