DP 17. Counts Subsets with Sum K | Dp on Subsequences

  Рет қаралды 244,921

take U forward

take U forward

Күн бұрын

Пікірлер: 1 000
@takeUforward
@takeUforward 3 жыл бұрын
I need your support, and you can do that by giving me a like, and commenting "understood" if I was able to explain you. The test case {0,0,1} has been explained in the DP 18 video.. Keeping a like target of 500 ❤✌🏼
@kartikaymahajan9591
@kartikaymahajan9591 3 жыл бұрын
Leetcode 473. Matchsticks to Square. I think this can be added to your playlist.it a variation of partition equal subset sum. what u say striver
@harshdasila6680
@harshdasila6680 2 жыл бұрын
@@kartikaymahajan9591 does this count subset with sum problem available on leetcode?
@vishalkumarshaw9208
@vishalkumarshaw9208 2 жыл бұрын
You deserve a million like striver... ❤️
@amitranjan6998
@amitranjan6998 2 жыл бұрын
@take U forward : I am loving your video and learning alot , I have one small confusion ,inside second for loop why you started sum=0 -> target in tabulation format ,why not start with sum=1 -> target;
@alltechpoint8508
@alltechpoint8508 2 жыл бұрын
done target
@tc2games176
@tc2games176 2 жыл бұрын
This is so nice that even if you have covered the concept(specific pattern), you are repeating it for the other variants of the question, so that it remains on the brain, it takes a lot of effort to do that, Thank you so much for all you do.
@anuragpandey8165
@anuragpandey8165 2 жыл бұрын
OMG you are magical, I was able to write recursive soln on my own, then memoized it on my own, tabulated as well as space optimized on my own before looking the video! I am making progress. All because of you.
@avneeshgoyal4554
@avneeshgoyal4554 2 жыл бұрын
map can be used for storing for negative values. where key is {index,sum}
@rishabhgupta9846
@rishabhgupta9846 2 жыл бұрын
can you share solution using map ,I'm getting wrong answer
@thomasshelby6780
@thomasshelby6780 7 ай бұрын
since when map is defined like that ,it must be map mp;
@indraneel6601
@indraneel6601 2 жыл бұрын
That was just amazing. I've actually done this problem from scratch without even watch this video which took me around 45 min(recursion, memoization, tabulation and Space optimization). Raj Sir you are just astounding
@drago3393
@drago3393 Жыл бұрын
For anyone facing a problem in the test case - {0, 0, 1} Just sort the given nums array in descending order. It will make the array {1, 0, 0} and will consider all the subsets containing zeros.
@lakeshkumar1252
@lakeshkumar1252 Жыл бұрын
thanks bhai
@MadhavGupta-fi2tu
@MadhavGupta-fi2tu Жыл бұрын
or else u can count number of zeros and return pow(2,n)
@vaibhavjaiswal7811
@vaibhavjaiswal7811 Жыл бұрын
Wow! This really blew my mind. So simple. Thanks
@yashhokte1020
@yashhokte1020 Жыл бұрын
Bro intuition behind it? Why we need to sort it in descending order?
@karthik53r35
@karthik53r35 Жыл бұрын
@@yashhokte1020 doing that will make all zero's behind thus considering both not pick and pick counts while adding
@divyanshbalisterverma1734
@divyanshbalisterverma1734 2 жыл бұрын
Understood, even solved without watching video.... Best DP series on any platform.💯💯💯💯💯
@2xReturns-FOOTBALL
@2xReturns-FOOTBALL Жыл бұрын
striver's love for lec-7 is unreal
@INTO2509
@INTO2509 6 ай бұрын
same dp bro
@ranjeet_sohanpal
@ranjeet_sohanpal 4 ай бұрын
Thala for a reason
@parthsalat
@parthsalat 2 жыл бұрын
*Code timestamps* Recursion: 15:00 Memoization: 20:50 Tabulation: 33:50 *Complexities timestamps* Recursion: 15:40 Memoization: 21:08
@DeepthiAcharya-xk8uz
@DeepthiAcharya-xk8uz 3 ай бұрын
lecture 16 ka negative testcase ko handle kaise kare, uska bhi timestamp bataado na bhayya
@subratsahai2017
@subratsahai2017 3 жыл бұрын
we can use map, understoodd
@aditianand6966
@aditianand6966 Жыл бұрын
best part "lecture seven is the most important in the whole universe"
@ketanwani8614
@ketanwani8614 10 күн бұрын
Thanks Striver. Your methods are making learning DP problems especially the tabular methods pretty easy and interesting. I was scared solving these problems before I started watching your videos. BTW, the case where we have '0' in the input should be solved using tabulation method as below: int perfectSum(vector& arr, int target) { vectordp(arr.size(), vector(target+1, 0)); for(int index = 0 ; index < arr.size() ; index++) { for(int j = 0 ; j
@manishprajapati8544
@manishprajapati8544 2 жыл бұрын
I done this question without watching this video in just 26 min. My concepts are getting crystal clear thanks Raj VikramAditya 🤩🤩🤩
@aryankumar87771
@aryankumar87771 2 жыл бұрын
it's not "just" 26 min, this is a 10 min problem
@mgfreefirelover4471
@mgfreefirelover4471 2 жыл бұрын
I'm also brother do this problem without watching the video ☺️
@manishprajapati8544
@manishprajapati8544 2 жыл бұрын
@@mgfreefirelover4471 sahi hai bhai karte jao ✨
@aryankumar87771
@aryankumar87771 2 жыл бұрын
@tokyo9570 to formulate the solution on paper - 5 min ( if never seen this problem before ), to code - another 5 min
@anshumaan1024
@anshumaan1024 2 жыл бұрын
@Tokyo haha, bro its 1 min problem, depends on your typing speed🤭
@animeshbarole
@animeshbarole Жыл бұрын
Understood, even solved without watching video.... Best DP series on any platform.
@subhajitdey135
@subhajitdey135 11 ай бұрын
I think the condition "if (target==0) return 1 " at 13:15 will not be totally valid if we have numbers like 0 in the array. So it will possibly be best if we check at the end for every possible subsequence. And Like if we don't have any number like 0 in the array, then this condition would be totally valid.
@TheK_Fam
@TheK_Fam 10 ай бұрын
you could just add that extra condition if i == 1: ways = 0 if remaining == 0 and arr[0] == 0: # If the only item is 0 and remaining sum is 0, there are 2 ways (include or exclude the 0) ways = 2 elif remaining == 0 or remaining == arr[0]: # If remaining sum is 0 or equals the only item, there's 1 way ways = 1 return ways
@TheK_Fam
@TheK_Fam 10 ай бұрын
dp = [[-1 for _ in range(k + 1)] for _ in range(n + 1)]
@ShubhamKumar-re4zv
@ShubhamKumar-re4zv 9 ай бұрын
Yes you are correct
@divy04
@divy04 8 ай бұрын
or we can store the non zero elements in some other array, pass it in the function, count the number of zero elements, and multiply the answer by 2^count
@after_dark_777
@after_dark_777 8 ай бұрын
@@divy04 your trick is failing in the 48th test case
@karanprabhakar72
@karanprabhakar72 3 жыл бұрын
use map to save (pair of index target) Will work for negative cases One point to remember " this code wont work when the array contains 0 itself , hence a little modification is required Remove 0 from the nums array and change return statements when target == 0 , return 2 instead of 1 1 for the indexes taken 2 for the index taken + 0 added.
@SasukeUchiha-jb6rf
@SasukeUchiha-jb6rf 3 жыл бұрын
Hi Karan, can you elaborate how to use map for negative cases? Like how map works, I mean pair signifies what and what does second int parameter of map signifies? It would be of great help
@karanprabhakar72
@karanprabhakar72 3 жыл бұрын
@@SasukeUchiha-jb6rf pair of int and int First index from ( n-1 to 0) and other int represents sum formed so far
@karanprabhakar72
@karanprabhakar72 3 жыл бұрын
@@SasukeUchiha-jb6rf let ne add code for it
@saunaknandi1814
@saunaknandi1814 3 жыл бұрын
@@karanprabhakar72 can u send the whole code
@chayalprabhakar7243
@chayalprabhakar7243 21 күн бұрын
@karanprabhakar can u share the code in java :P
@AnushkaGupta-x6w
@AnushkaGupta-x6w Жыл бұрын
All those asking why 2nd loop in tabulation starts from sum=0 and not 1 because because , guys we have to tell totals subsets with sum= target so if we have had target=0 then you would have already stored the answer of dp[n-1][0]=1 Which is correct if arr did not have any integer as 0 , in case 0 are there then this subset with 0 is also a valid answer hence we need to count it as well eg arr=[0,2 3] target=0 so total answer is 2 not 1, so we recalculate the value of dp[i][0] to ensure if we are getting any more subsets with sum=0 apart from the empty subset. I hope you understood my point
@pranaykumar9186
@pranaykumar9186 6 ай бұрын
then it should be applied to all previous questions also , there second loop should also start from 0 instead of 1.
@kunalgupta343
@kunalgupta343 6 ай бұрын
Try with [0,1,0] with target 0.
@AnushkaGupta-x6w
@AnushkaGupta-x6w 6 ай бұрын
@@kunalgupta343 4 i guess, All subsets possible are- Null 0 a first index 0,0 0 at last index
@biswajitadhikary_0807
@biswajitadhikary_0807 5 ай бұрын
@@AnushkaGupta-x6w it is 3 0 0 0 0
@clashtm8210
@clashtm8210 5 ай бұрын
I can't comprehend that, can you rephrase what you have written?
@maradanikhil6882
@maradanikhil6882 Жыл бұрын
we can use "unordered_map" instead of vector for storing ,if there are negative numbers;
@Sumeet_100
@Sumeet_100 Жыл бұрын
but this still gives TLE ? isn't it ?
@muditkhanna8164
@muditkhanna8164 Жыл бұрын
unordered map cannot be used for 2d size , you should use map, as the internal implementatin u_map is hashtables ,which is not working for 2d size, meanwhile map could give you TLE because of extra log(N) insertion tc
@muditkhanna8164
@muditkhanna8164 Жыл бұрын
@@Sumeet_100 instead of using map , try to create a 2d vector and create a hashtable using this and fill the dp of pointers and indexes as target and ind , theoritically, it might work in 0(1),but its actually not 0(1), or you can create your own class just for simplified code.
@kushjoshi9427
@kushjoshi9427 Жыл бұрын
unordered map stores key, value pair you can use pair as the key to store index and target but to store that we have to create a custom hash function or you could just make the 2d matrix 2 times the value if it is -ve store it after n
@nodipankar677
@nodipankar677 7 ай бұрын
@@kushjoshi9427 we can use as unordered_map? isn't that correct?
@AshishGupta-bi4rh
@AshishGupta-bi4rh 2 жыл бұрын
One thing to note here is that if the array had 0 also as its element then we can't return 1 from the base case if(sum==0) we have to go to index==0
@satyamsingh7178
@satyamsingh7178 2 жыл бұрын
So what should be approach
@jeemains3524
@jeemains3524 2 жыл бұрын
@@satyamsingh7178 class Solution{ public: int fun(int pos, int sum, int arr[],vector &dp,int N) { if (pos == N) return sum == 0 ; int &ans = dp[pos][sum]; if (ans != -1) return ans; ans = 0; ans += fun(pos + 1, sum, arr,dp,N); if (arr[pos]
@GManiKarthik
@GManiKarthik 2 ай бұрын
Wow, what an incredible lecture! 🙌 I’ve finally understood and even implemented the recursion, memoization, tabulation, and space optimization code myself! 💻✨ You delivered exactly what you promised at the beginning of this DP series. 🔥👏 #Understood ✅ #DP17 🚀 #HatsOff 🎩 #Striver 💯
@rahulsrivastava9710
@rahulsrivastava9710 2 жыл бұрын
I did it my own...got stucked but cleared 😊 Thank you Bhaiya @Striver Bhaiya
@codermal
@codermal 2 жыл бұрын
map could be used for -ve integer case and btw understood💯
@rishabhgupta9846
@rishabhgupta9846 2 жыл бұрын
pls share solution using map ,I'm getting wrong answer
@_ANIKETVerma
@_ANIKETVerma 2 жыл бұрын
plese share the solution
@adityabhoyar5693
@adityabhoyar5693 5 ай бұрын
I think for negative integers we can take take the absolute value of the most negative integer and then do it like ele=abs(minvalue)+1 and then add this value to all the elements of the array as well as the target that we needed ,as the net difference between all the elements will be same .
@untitled6483
@untitled6483 4 ай бұрын
Took me 3 hrs. to do recursion, memorization and tabulation. But I learned how I should write recursion, memorization to be able convert it to next step.
@shivanshsingh176
@shivanshsingh176 2 жыл бұрын
There is an important test case to be considered : num : 1 0 0 1, target = 0 If you will place the base conditions like if(j==0) dp[i][j] = 1 in the for loop, then it will be wrong. That's the reason that base case is not defined in the loop. I had a habit of defining everything in the loop so 2 of my test cases were not running. That I realized this, it sure took time to realise this !!!
@chirlasowmyareddy
@chirlasowmyareddy Жыл бұрын
Understood!! minor change for arrays containing zeros -remove target==0 condition and add this if(ind==0) { if(target==0 && nums[0]==0) return 2; if(nums[0]==target || target==0) return 1; return 0; }
@mayurdas9738
@mayurdas9738 Жыл бұрын
can u explain, how you came to this solution and how it is helping us to solve the error that we are getting?
@anujrathore5726
@anujrathore5726 7 ай бұрын
thank you buddy
@kushalgupta2041
@kushalgupta2041 5 ай бұрын
bro your condition are correct but i think you forgot this case where you have not reached index = 0 but target is already achieved means target = 0 & ind != 0 but arr[idx] = 0 then you also have to count that case right so you have to also add this case: - if(target == 0 && arr[idx] != 0) return 1;
@TON-108
@TON-108 4 ай бұрын
Thanks bro!
@aryanmusicacademy944
@aryanmusicacademy944 2 ай бұрын
if(t < 0) return 0; if(ind == 0){ return (v[0] == t) + (t == 0); }; i did the same thing, the question stated "positive" values, but had 0 in the test cases.😭
@naveenvebuthi8357
@naveenvebuthi8357 10 ай бұрын
For testcase num={0,0,0,0} tar=0 answer should be 16, But code generating output as 1.
@anishkumarde5505
@anishkumarde5505 3 жыл бұрын
For storing we can use a map... Where target and index will be converted to string and then store it as a key with values
@nitishmishra9943
@nitishmishra9943 2 жыл бұрын
we can also use array for index and map for target (every element of indexe's array will contain map)
@rishabhgupta9846
@rishabhgupta9846 2 жыл бұрын
can you share the solution using map,I'm getting wrong answer
@Sumeet_100
@Sumeet_100 Жыл бұрын
​@@rishabhgupta9846 This code still give TLE #include const int mod = 1e9+7; int f(int i,int tar,vector&arr,unordered_map &dp){ if(tar==0){ return 1; } if(i==0){ return dp[0][tar] = (tar==arr[0]); } if(dp[i][tar]!=-1)return dp[i][tar]; int notpick = f(i-1,tar,arr,dp); int pick = 0; if(tar>=arr[i]){ pick = f(i-1,tar-arr[i],arr,dp); } return dp[i][tar] = (pick + notpick)%mod; } int findWays(vector& arr, int k) { // Write your code here. int n = (int)arr.size(); unordered_map m; for(int i = 0;i
@Sakthivel-zq1hb
@Sakthivel-zq1hb 5 ай бұрын
A whole hearted Thanks for your Efforts. And I hope you would get recognised by the big Institutes and Industries 🙂
@namansharma5128
@namansharma5128 Жыл бұрын
for handling the cases in which the array contains 0 --> use only one base condition --> if(ind < 0) return tar == 0; or you can use--> if(ind == 0){ if(num[0] == 0 && tar == 0) return 2; if(num[0] == tar || tar == 0) return 1; return 0; }
@VishalPatel_imvishal
@VishalPatel_imvishal Жыл бұрын
worked. thanks
@spiral546
@spiral546 Жыл бұрын
thx
@Prakhar-ie1wk
@Prakhar-ie1wk Ай бұрын
will not it fail for num : 1 0 0 1, target = 0 (2nd code)
@MukeshKumar-cc3uh
@MukeshKumar-cc3uh 11 ай бұрын
We can use a list of map to counter the negative values in the array or a negative target. And maybe, there we don't have to check(before picking/taking), if the curr. value is less than target or not, as in future, there is a possibility of -ve ints. "Understood" Striver .👍
@craftanddiy4773
@craftanddiy4773 6 ай бұрын
can u provide the code
@girishbhargava6367
@girishbhargava6367 2 жыл бұрын
Striver, I think you are referring to the usage of map. Please correct me if I am wrong... Your explanation is extremely intuitive.
@mrinmoyhalder7293
@mrinmoyhalder7293 2 жыл бұрын
I also thinking same, but then in map, key will be pair and value in single int.isn't it ??
@rishabhgupta9846
@rishabhgupta9846 2 жыл бұрын
can you share the code using map
@HimanshuSingh-rm5sd
@HimanshuSingh-rm5sd Жыл бұрын
@@mrinmoyhalder7293 we can use map like key will be for indexes 0 to n-1 and value will be a vector of int ie like columns in matrix or sum
@Jdnrjndkejdn
@Jdnrjndkejdn 16 күн бұрын
can anyone help me i dont understand this sum becomes negative i mean the dp matrix store the count which will be either zero or some positive nos what is the point of using extra data structures????
@niloychowdhury4729
@niloychowdhury4729 2 ай бұрын
I did in this way.Just carry an extra arguement cur_sum and whenever the function calling reaches at it's base case(indn>>k; vectora(n); for(auto &it:a) cin>>it; vectordp(n,vector(k+10,-1)); cout
@goooo9561
@goooo9561 2 жыл бұрын
Codes that work even for multiple zeroes: Top Down/Memoization: Time complexity:O( n*sum ) Space Complexity:O( n*sum+n ) int helper(int arr[],int k,vector &dp,int i) { if(dp[i][k]!=-1) return dp[i][k]; if(i==0) { return 0; } int inc=0,exc; if(arr[i]
@HoppyGamer
@HoppyGamer 2 жыл бұрын
Thank you so much was stuck on this for hours
@ISHARAMTEKE-ku2ll
@ISHARAMTEKE-ku2ll Жыл бұрын
Thank you
@arvindjaiswal8013
@arvindjaiswal8013 7 ай бұрын
Use Map where the key will be and the value will be the state of the sum.
@craftanddiy4773
@craftanddiy4773 6 ай бұрын
can u provide me the code
@sagarbathla5160
@sagarbathla5160 2 жыл бұрын
Hi Striver. Thanks for the great explaination. but i have one doubt why are we starting the nested loop of target from 0. It should start from 1 right. Since we already covered the 0 case in our base case.
@rocklee3254
@rocklee3254 2 жыл бұрын
watch his next lecture u will come to know about it
@siddhiparsekar
@siddhiparsekar 2 жыл бұрын
hey, i got the same doubt...did you get it why he started from 0 and not 1 like before?
@VishalKumar-yc3wr
@VishalKumar-yc3wr Жыл бұрын
Bhai explain kar do
@shreyanshpatil8303
@shreyanshpatil8303 Жыл бұрын
start with 1 still it gives the correct output
@pranavkumar1543
@pranavkumar1543 2 ай бұрын
@@VishalKumar-yc3wr We can have target as Equal to Zero, That's why we start from Zero for the target /sum loop
@Code_With_Goat
@Code_With_Goat Жыл бұрын
small correction here : if( a[0]
@GauravKumar-wk9tr
@GauravKumar-wk9tr 11 ай бұрын
Ther is Slight change u can make for 0s : 1-->Don't simply return if u reach to Target , go beyond even you reached target as there can be multiple Zeros that will Also make the another combinations 2-->while returning pick+notPick add a supportVal to it by checking if(target-arr[currIdx[)==0)supportVal++; it simply states that u can reach to the target at this index also so add 1 to your ans; int solve(vector& arr, int idx, int target, vector& dp) { if (idx == 0) return (target == arr[idx]) ? 1 : 0; if (dp[idx][target] != -1) return dp[idx][target]; int notPick = solve(arr, idx - 1, target, dp); int pick = 0; if (target >= arr[idx]) pick = solve(arr, idx - 1, target - arr[idx], dp); int supportVal=0; if(target-arr[idx]==0)supportVal++; return dp[idx][target] = (pick+notPick+supportVal) % MOD; }
@SouravKumar-um7pr
@SouravKumar-um7pr 8 ай бұрын
What is MOD
@untitled6483
@untitled6483 4 ай бұрын
So how this base case can be written in tabulation.
@aryanrastogi1335
@aryanrastogi1335 2 жыл бұрын
if sum will negative we can use map.
@sujayshanbhag2055
@sujayshanbhag2055 2 жыл бұрын
Understood!! minor change for arrays containing zeros -remove target==0 condition and add this if(ind==0) { if(target==0 && nums[0]==0) return 2; if(nums[0]==target || target==0) return 1; return 0; } P.S :- take you forward viewers make the best community :)))
@abhishekpandey0295
@abhishekpandey0295 2 жыл бұрын
nice brother
@VIRAJBHOSLE
@VIRAJBHOSLE 2 жыл бұрын
Here is the tabulation for edge cases: arr 0, 0, 0 and target 0 arr 0, 0 , 1 and target 1 public static int subsetSumToK(int n, int k, int arr[]){ int[] curr = new int[k+1]; int[] prev = new int[k+1]; prev[0] = 1; curr[0] = 1; if(arr[0]
@RahulGuptaa29
@RahulGuptaa29 Жыл бұрын
oh bhai GFG main 4 ghante se sir phod raha tha! thanks yaar
@aas-vlog1
@aas-vlog1 Жыл бұрын
nice brother because i was trying to solve this problem on gfg
@kgdfcr2347
@kgdfcr2347 Жыл бұрын
​@@aas-vlog1 bro gfg pe case 104 galat aruha hai yeh logic ke baad bhi can u pls help
@neptune25
@neptune25 2 жыл бұрын
for multiple zeros change this base case if(nums[0]
@anishpatro
@anishpatro Жыл бұрын
tq bro
@zhunzargulhane6741
@zhunzargulhane6741 Жыл бұрын
what is wrong here with my code. Could you please help with it. public static int findWays(int nums[], int sum) { int[][] memo = new int[nums.length][sum+1]; for(int i=0;i
@dharmeshpoladiya9047
@dharmeshpoladiya9047 2 жыл бұрын
Understood 💯💯 Great Explanation. Thank you very much for all you efforts🔥🔥
@AlokLaha-te2pd
@AlokLaha-te2pd 7 ай бұрын
Thanks Striver. Understood it very well. For negative indexes we can use map where keys will be pair of index, sum
@PratikPatil
@PratikPatil Жыл бұрын
unordered_map or map can be used to store the negative states of target
@Codebreaker0702
@Codebreaker0702 Жыл бұрын
@take U forward at 24:27 , we can also write base case as if(ind==0) return dp[0][a[0]] == true; . It worked for me.
@shobhit351
@shobhit351 3 жыл бұрын
Love all videos but 1 suggestion Pls at the end mention the best time and space complexity in which a ques can be solved (which may not be attained by DP, but just mentioning it will help as i can search and study that best method which will help me interview )
@ayushnath3768
@ayushnath3768 2 жыл бұрын
the last code is the most optimized one
@bhagatalisha
@bhagatalisha 5 ай бұрын
Watching Striver is like getting your fundamentals at place!
@adityashrivastav4983
@adityashrivastav4983 3 жыл бұрын
Please provide leetcode link also
@riderpd09
@riderpd09 3 жыл бұрын
Bhaiya subset wale problem mai take nottake wala meta itna achha se samajh gaya hu ki ab apka videos 2x mai bhi full samajh mai araha hai :))
@johncenakiwi
@johncenakiwi 3 жыл бұрын
Raj, can you please also do a lecture on Longest Increasing Subsequence? You have already explained the tabulation solution on your channel but can we also have the recursive solution with the memoization solution where we use a 1D array for memoization? Thank you.
@omkarpatil5045
@omkarpatil5045 7 ай бұрын
Excellent!!But small correction in the base case that is if arr[0]==0 then there can be 2 possibilities hence.. if(arr[0]==0){ prev[arr[0]]=2; } else if (arr[0]
@jayantgoyal3311
@jayantgoyal3311 7 ай бұрын
is your code submitting correctly on code studio? mine is getting partially accepted
@jayantgoyal3311
@jayantgoyal3311 7 ай бұрын
Done. i forgot to take modulo with 1e9+7
@ranasauravsingh
@ranasauravsingh 2 жыл бұрын
UNDERSTOOD... ! map data structure... ? for negative input integers... Thanks for the video... :)
@KapilSharma56419
@KapilSharma56419 7 ай бұрын
// Handling the first element of the array separately if (arr[0]
@pawanharwani4598
@pawanharwani4598 3 жыл бұрын
If there are non-negative integers and sum can also be non-negative then we can use map data structure but what if given array is arr[] = {0,0,0,0,1} and required sum is 0, in this case our code will return 1 as answer but the actual ans is 16. This case is occuring due to that base case condition i.e if (sum==0) return 1, so how will we handle this case.
@takeUforward
@takeUforward 3 жыл бұрын
Thats a valid question, let mr address this in the next video.
@Aks-47
@Aks-47 3 жыл бұрын
@@takeUforward sum==0 and ind==0 return 1; handles this!
@bharathkumar5870
@bharathkumar5870 2 жыл бұрын
ans is not 16,ans is 1 only..{0,0} is not a set it boils down to {1}
@Aks-47
@Aks-47 2 жыл бұрын
@@bharathkumar5870 first understand the question, and then cross question.. This set is different from "set" data structure
@shivangagrawal2923
@shivangagrawal2923 2 жыл бұрын
@@takeUforward solution?
@Mr.codinghacker
@Mr.codinghacker 11 ай бұрын
congrats for 500k subscribers bhaiya
@hashcodez757
@hashcodez757 6 ай бұрын
if facing wrong answers, that might be due to the inclusion of zeroes into the test cases. for example: [0, 5] if you'll try to draw a recursion tree then you'll definitely get it. According to the base conditions: if(target == 0) return 1; this will then and there only stop the further recursive calls even if the element might be zero which results in wrong answer. new Base conditions are: if(n
@madhu_mohanreddy
@madhu_mohanreddy 5 ай бұрын
im still getting error can yu post the code
@hashcodez757
@hashcodez757 2 ай бұрын
Recursive Code(not memoized and tabulated) class Solution{ public: int fn(int idx, int sum, int arr[]){ if(idx
@ranjeet_sohanpal
@ranjeet_sohanpal 4 ай бұрын
For the test {0,0,1}, just put dp[0][arr[0]] = 2, this will make sure both the pick and notpick are considered when the first element is zero.
@piyushsaxena6243
@piyushsaxena6243 3 жыл бұрын
understood , love ur explanation of each and every problem
@theunknown1333
@theunknown1333 Жыл бұрын
for handling zeroes, since k>=1 we can sort in decreasing order...and just write the same code and it will handle all the zeroes.... ::)
@dishagupta7446
@dishagupta7446 2 жыл бұрын
In case of negative numbers we can use hashmap
@iamnoob7593
@iamnoob7593 Жыл бұрын
yes
@TheDebuggers-fx9vp
@TheDebuggers-fx9vp 5 ай бұрын
i thnk a sligh change in base case can handle all the case well,instead of returning when we encounter the target to 0; if we keep exploring until the end of the tree then we can get our desired result class Solution { public: int helper(int arr[], int n, int sum, vector& dp) { // Base case: If there are no elements left if (n == 0) { return (sum == 0) ? 1 : 0; } // If the subproblem has already been solved, return the stored result if (dp[n][sum] != -1) return dp[n][sum]; // Compute the result for this subproblem int notPick = helper(arr, n - 1, sum, dp); int pick = 0; if (arr[n - 1]
@RaghavSharma-nt3hr
@RaghavSharma-nt3hr 2 жыл бұрын
NOTE: CASE OF- if(target==0 && arr[0]==0) return 2;
@codysaurabh
@codysaurabh 11 ай бұрын
Why
@KrishnaGuptaTech
@KrishnaGuptaTech Ай бұрын
We can use hashmap, that didn't even clicked my mind, Understood boss !!!
@humbleGuy_1729
@humbleGuy_1729 2 жыл бұрын
We will get overlapping subproblems only when there are duplicate elements in the array (talking only for this particular problem)
@tanmayrauth7367
@tanmayrauth7367 2 жыл бұрын
No thats not true. You get overlapping sub problem because for solving big problem you break it into pieces and then there is possibility that small piece might have been solved previously
@humbleGuy_1729
@humbleGuy_1729 2 жыл бұрын
@@tanmayrauth7367 i was speaking only for this problem bro..
@srcodes13
@srcodes13 8 ай бұрын
For anyone struggling with the test cases not passing, the constraints of the problem have been changed, the array can contain zeros now. Just go to the DP 18 video in case you need an explanation.
@vaibhavdeshmukh7900
@vaibhavdeshmukh7900 2 жыл бұрын
I feel this code is not considering the case when multiple zeroes are present in the array. We can't directly return 1 when we encounter tar == 0; that won't consider zeros present in the array after the index when we got the sum ==0 while doing the recursion. EX Test Case where the above code will fail: n = 4, target = 3 elements: 0 0 3 3 PS: This issue has been discussed in the following video.
@tarunkumar3279
@tarunkumar3279 2 жыл бұрын
which video
@HARSHPIPAL
@HARSHPIPAL 2 жыл бұрын
sir,you can directly write single base case for recursive part (if ind==-1) if(target==0) return 1; else return 0;
@kushalgupta2041
@kushalgupta2041 5 ай бұрын
brother but in this case you are increasing time complexity quite right? because when you find target you have to iterate over all not take possible sum of it till you reach idx == -1 right? so why don't we do this:- if(idx == 0) { if(target == 0 && arr[idx] == 0) return 2; if(target == 0 || target - arr[idx] == 0) return 1; return 0; } if(target == 0 && arr[idx] != 0) return 1;
@Anschlusss
@Anschlusss Жыл бұрын
Understood!!! ❤❤❤. Just in case if anyone wanted the solution for negative numbers, Here it is.... #include using namespace std; class Solution{ public: int solve(vector arr,int sum,int index,map &dp){ if(index==0){ if(sum==0 && arr[0]==0) return 2; else if(arr[0]==sum || sum==0) return 1; else return 0; } if(dp[{index,sum}]!=0) return dp[{index,sum}]; int nottake = solve(arr,sum,index - 1,dp); int take = 0; if(arr[index]0) take = solve(arr,sum - arr[index],index - 1,dp); else if(arr[index]>=sum && sum
@Surya-ej4zf
@Surya-ej4zf Жыл бұрын
if(sum==0 && arr[0]==0) return 2; why this line??
@as.if_0077
@as.if_0077 Жыл бұрын
@@Surya-ej4zf watch the next lecture or else draw recursion tree
@ShubhamKumar-re4zv
@ShubhamKumar-re4zv 9 ай бұрын
Base case is incorrect It should be if(index==0){ if(sum==0) return 1; return 0; } Other wise for arr{1,0,2,3} this code will give output 3 but the correct output is 4. Article of this problem is also incorrect ,There should be a option to add comment to the article or any other way to inform about the incorrect code
@yoginpahuja5557
@yoginpahuja5557 2 жыл бұрын
arr=9,7,0,3,9,8,6,5,7,6 target =31 it fails correct output =40 it gives 37 Please update the correct solution
@parushgarg4512
@parushgarg4512 2 жыл бұрын
is you able to find the mistake?
@sahilgagan2242
@sahilgagan2242 2 жыл бұрын
i got correct answer
@dhanushb5203
@dhanushb5203 2 жыл бұрын
You should handle the zeroes, the explained code in this video works only on arr[i]>0. Lets talk about your testcase. Assume you have no '0' in your input, then you will get ans as 20. Now include '0', i.e adding element '0' to 20 subsets. Final ans = 20 (without zero) + 20 (with zero) = 40. Hope it clears your doubt.
@shahrukhansari7806
@shahrukhansari7806 2 жыл бұрын
Sort the array
@Steve-kv5we
@Steve-kv5we 2 жыл бұрын
Yes, you are right it will give wrong answer in cases of 0. public static int Memoization(int idx, int[] arr, int target, int[][] dp){ if(idx==0){ if(target==0 && arr[0]==target) return 2; else if(arr[0]==target || target==0) return 1; else return 0; } if(dp[idx][target]!=-1) return dp[idx][target]; int notTake = Memoization(idx-1,arr,target,dp); int take = 0; if(arr[idx]
@swapnilingale4164
@swapnilingale4164 Жыл бұрын
It's ok to use unorderd map
@anveshkarra3861
@anveshkarra3861 2 жыл бұрын
i think we can use hash map for negative numbers
@anmol3749
@anmol3749 Ай бұрын
Understood Thank you striver
@mayankbharti531
@mayankbharti531 2 жыл бұрын
if you guys are getting 11/13 test cases passed in tabulation then try adding:- if(num[0] == 0) dp[0][0] = 2; after the given two conditions.
@akarshitkumar6744
@akarshitkumar6744 2 жыл бұрын
thnx, i am searching for same problem
@Noobdie2779
@Noobdie2779 Жыл бұрын
Thanks it worked😊
@CodeAndThrive
@CodeAndThrive Жыл бұрын
yeah it worked! may u explain it?
@yashrawat5158
@yashrawat5158 Жыл бұрын
can you explain this?
@varunsharma5582
@varunsharma5582 Жыл бұрын
@@CodeAndThrive ​ @yashrawat5158 Because if very first element has value 0 and target is 0, it can contribute twice, once by taking it and once by skipping it. So, it can add value to two different kinds of subsets one that take it and ones that don't {0} also has a sum of 0 and {} also has a sum of 0, similarly if second element was also 0, there will be similar permutations and combinations.
@hashcodez757
@hashcodez757 6 ай бұрын
"UNDERSTOOD BHAIYA!!"
@rohitraj5832
@rohitraj5832 2 жыл бұрын
@Striver, you are missing here 1 thing, what if nums[0]=0 and target =0 .in memoization case. then from the first base condition it get returns but, it should increase subset count . bcz on adding 0 , there is no change in the target. but subset count changes. IN GFG your code is giving wrong answer. you code is not getting accepted because we are not doing "INCLUSION AND EXCLUSION on index=0" . plz reply.
@sameera3839
@sameera3839 2 жыл бұрын
hey. what do you mean ?
@ankurshahi9527
@ankurshahi9527 2 жыл бұрын
Thank you Rohit, I was also trying to figure out what went wrong in the code. Base case: if(index < 0) { return target == 0;}
@Steve-kv5we
@Steve-kv5we 2 жыл бұрын
@@sameera3839 He means if we are at index 0 and target is also = 0, then we should return 2 not 1 because we can consider taking that 0 in our subset as well as we can consider not taking it in our subset and thus 2 different subsets will be formed including 0 and not including 0. Hence, we should return 2 in that case.
@YVGamers
@YVGamers 2 жыл бұрын
@@Steve-kv5we thanks have a good understanding from this
@tridibeshmisra9426
@tridibeshmisra9426 2 жыл бұрын
why ? the question states that all the numbers are positive it means 0 is not included that's why striver has not done any mistake.
@shreyasnagabhushan4918
@shreyasnagabhushan4918 2 жыл бұрын
we can use dictionaries to store DP instead of 2D array, if negative integers are present in array .
@niravsingh4532
@niravsingh4532 3 жыл бұрын
The linked problem is different.
@thebibeksaha
@thebibeksaha 2 жыл бұрын
Map> maybe?
@vanshsehgal9475
@vanshsehgal9475 2 жыл бұрын
Rather than using maps,we can do some mathematics and find the most negative sum that we would ever get and then adjust the size of mat accordingly. Like if most -ve sum is -100, then we can add 100 to our most positive sum we can get and everytime while accessing sum in the matrix, we will always write [sum+100], so that -ve sums are also handled, but yeah there can be issues regarding matrix size, it may become large enough that we can't even use it for memoization. But yeah its a way we can apply.
@himansh4812
@himansh4812 Жыл бұрын
@32:00 We can use unordered map to store sum and index pair. When sum can be negative.
@craftanddiy4773
@craftanddiy4773 6 ай бұрын
can u provide the code
@sunilpanchal1498
@sunilpanchal1498 2 жыл бұрын
Understood, and we can use unordered_map for negative values.
@naamhaii
@naamhaii Жыл бұрын
unordered_map u;
@SarvanShivani234
@SarvanShivani234 7 ай бұрын
indeed taking us forward😊
@himanshuagrawal8012
@himanshuagrawal8012 2 жыл бұрын
We can use UNORDERED_MAP to handle -ve values as we dont need our keys to be in sorted order, so O(n*m) space complexity will be there.
@7akon
@7akon 2 жыл бұрын
I think an ordered map would be used. An unordered map wouldn't support a pair as a key. We need a pair as key as the key pair is (index, sum). An ordered map however will support it.
@codingwithanonymous890
@codingwithanonymous890 2 жыл бұрын
@@7akon right
@priyak8786
@priyak8786 2 жыл бұрын
@@7akon yeah
@parthsalat
@parthsalat 2 жыл бұрын
@@7akon Thanks for the hint
@ankursingh8296
@ankursingh8296 2 жыл бұрын
But what will be the base case
@sumitpadadune3763
@sumitpadadune3763 Жыл бұрын
understood sir thanks for such great series on DP
@Steve-kv5we
@Steve-kv5we 2 жыл бұрын
Understood 💯💯 The Memoization code to handle subsets containing 0's -> public static int Memoization(int idx, int[] arr, int target, int[][] dp){ if(idx==0){ if(target==0 && arr[0]==target) return 2; else if(arr[0]==target || target==0) return 1; else return 0; } if(dp[idx][target]!=-1) return dp[idx][target]; int notTake = Memoization(idx-1,arr,target,dp); int take = 0; if(arr[idx]
@saunaknandi1814
@saunaknandi1814 2 жыл бұрын
steve can u make me understand this if(idx==0){ if(target==0 && arr[0]==target) return 2; else if(arr[0]==target || target==0) return 1; else return 0; }
@rishabhgupta9846
@rishabhgupta9846 2 жыл бұрын
@@saunaknandi1814 here we are not using if target==0 return 1 as the base case ,because if we use then it will return without coming to index 0 then we are avoiding the 0 present at index 0.But if we above condition. Then it will go till index 0 and check of target is 0 and value at index 0 is 0 then return 2 for else if target== 0 then return 1 or if current value(value at index 0)is equal to target then return Else return 0
@AmitPrajapati-ul4ei
@AmitPrajapati-ul4ei 2 жыл бұрын
@user-ht9fr8sd8u op vai
@romanreigns4235
@romanreigns4235 Жыл бұрын
@@rishabhgupta9846 thanks bro 😊
@yashshukla1637
@yashshukla1637 Ай бұрын
Awesome Video Brotha!
@sahilgoyals
@sahilgoyals 3 жыл бұрын
map data-structure in c++ for handling -ve sum
@SasukeUchiha-jb6rf
@SasukeUchiha-jb6rf 3 жыл бұрын
Hi Sahil, how can we use map for -ve sum? Can you elaborate with a example
@sahilgoyals
@sahilgoyals 3 жыл бұрын
@@SasukeUchiha-jb6rf we can use map for any type of key as well just convert all the changing parameters to string amd store them Eg: Changing parameters are i and j String key = to_string(i) + "-" + to_string(j); And them in unordered_map
@DeepanshChawla_
@DeepanshChawla_ 2 жыл бұрын
@@sahilgoyals we can use nested maps as well 😊 but i know that will add up the tc 🙂
@consistency_Is_key
@consistency_Is_key 7 ай бұрын
understood , my question is can we run the sum loop from 1 rather than 0 , as sum =0 is already calculated
@AvishekChatterjee
@AvishekChatterjee 2 жыл бұрын
UNDERSTOOD but @take U forward why are we making so much mess in the base case we can simply write if (index < 0) { if (sum == 0) return 1 ; else return 0 ; }
@bishnoi6409
@bishnoi6409 2 жыл бұрын
then you cannot write tabulation method easily.
@Flynn-lk8im
@Flynn-lk8im 11 ай бұрын
⚠ If you are getting wrong answer on some test cases, the culprit is the 0s in the array. So final answer will be `ans + ans * number of combinations of n 0s`. The number of combinations of n 0s is just the nth triangular number i.e `n * (n + 1) / 2`.
@karthikmohan79
@karthikmohan79 3 жыл бұрын
web/app Dev guys: DSA, CP is overrated. Complex projects exists: Searchs internet,stack overflow ends up with no solution. DSA CP guys: here you go.
@ByteBattle123
@ByteBattle123 2 жыл бұрын
Understood 🔥🔥🙏 thank you very much for your hard work🛐
@maheshnagasai5466
@maheshnagasai5466 Ай бұрын
This code fails when target is 0 in memoization. for that initially check if target is 0 , if it is zero then count total zeros and return 2^(Total Zeros)
@gunduboinadileep9523
@gunduboinadileep9523 Жыл бұрын
understand!!. I think maps are the data structures where we can store data with negative indices.
@siddharthgowd825
@siddharthgowd825 Ай бұрын
for those including 0's : use base case -> if index
@illtaR
@illtaR 27 күн бұрын
what if theres intermediate zero?
@mayanksinghal9315
@mayanksinghal9315 Жыл бұрын
For anyone facing the problem with {0, 0, 1} scenario. They can use shifting of index explained in video DP25 - LCS.
@harshit4190
@harshit4190 3 жыл бұрын
For storing -ve sum we can make dp of size , row = N and column = totalArraySum * 2 + 1, so left half will store for negative sum and right for positive sum
@puneetchhabra2278
@puneetchhabra2278 3 жыл бұрын
This will give array out of bound exception because for a test case like 1 ,2,3,-5 the sum will be 1 and size of col will be 3 , for sub array 1,2,3 the sum will be 6 which is out of bound.
@puneetchhabra2278
@puneetchhabra2278 3 жыл бұрын
It will be better to go with map DS to mark the sums as hinted in the video .
@adheeshmishra7882
@adheeshmishra7882 2 жыл бұрын
@@puneetchhabra2278 take the sum of positive numbers only for dp matrix declaration...just a way around it...map suggested...
@puneetchhabra2278
@puneetchhabra2278 2 жыл бұрын
@adheesh Mishra , extra o(n) time will be required to find the max positive sum and what if the target sum is negative
@SajanKumar-ec2us
@SajanKumar-ec2us 9 ай бұрын
all test cases satisfying your code now
@Review17a
@Review17a Жыл бұрын
firstly lots of respect for striver, striver code is failed on some test cses testcases ,beccause there is possible overlaaping,normally inclusion exclusion does not have over lapping subsequences but here if sum is going to be neqative then we we have to stop that subsequences so threre is possiblitiy that overlapping occur for solving this issue we need to finish element in increasing order code: #include using namespace std; int findWaysUtil(int ind, int target, vector& arr, vector &dp){ if(target==0) return 1; if(ind == 0) return arr[0] == target; if(dp[ind][target]!=-1) return dp[ind][target]; int notTaken = findWaysUtil(ind-1,target,arr,dp); int taken = 0; if(arr[ind]
@prabhakaran5542
@prabhakaran5542 11 ай бұрын
Understood ❤
DP 18. Count Partitions With Given Difference | Dp on Subsequences
18:00
How to treat Acne💉
00:31
ISSEI / いっせい
Рет қаралды 108 МЛН
To Brawl AND BEYOND!
00:51
Brawl Stars
Рет қаралды 17 МЛН
Сестра обхитрила!
00:17
Victoria Portfolio
Рет қаралды 958 М.
Леон киллер и Оля Полякова 😹
00:42
Канал Смеха
Рет қаралды 4,7 МЛН
What does it feel like to invent math?
15:08
3Blue1Brown
Рет қаралды 4,2 МЛН
5 Secrets to Stop Stuttering & Speak More Clearly!
12:44
Vinh Giang
Рет қаралды 120 М.
AI Is Making You An Illiterate Programmer
27:22
ThePrimeTime
Рет қаралды 213 М.
The Mathematician So Strange the FBI Thought He Was a Spy
13:11
Fast Inverse Square Root - A Quake III Algorithm
20:08
Nemean
Рет қаралды 5 МЛН
one year of studying (it was a mistake)
12:51
Jeffrey Codes
Рет қаралды 293 М.
How to treat Acne💉
00:31
ISSEI / いっせい
Рет қаралды 108 МЛН