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

แชร์
ฝัง
  • เผยแพร่เมื่อ 20 ก.ค. 2024
  • Lecture Notes/C++/Java Codes: takeuforward.org/dynamic-prog...
    Problem Link: bit.ly/3B5JBkU
    Pre-req for this Series: • Re 1. Introduction to ...
    a
    Make sure to join our telegram group for discussions: linktr.ee/takeUforward
    Full Playlist: • Striver's Dynamic Prog...
    In this video, we solve the problem of count subsets which gives sum equal to K. This problem is the fourth problem on DP on Subsequences Pattern. Please watch DP 14 before watching this.
    If you have not yet checked our SDE sheet, you should definitely do it: takeuforward.org/interviews/s...
    You can also get in touch with me at my social handles: linktr.ee/takeUforward

ความคิดเห็น • 902

  • @takeUforward
    @takeUforward  2 ปีที่แล้ว +318

    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 2 ปีที่แล้ว +5

      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 ปีที่แล้ว +1

      You deserve a million like striver... ❤️

    • @amitranjan6998
      @amitranjan6998 ปีที่แล้ว +1

      @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 ปีที่แล้ว

      done target

  • @user-qq5bb7bh5z
    @user-qq5bb7bh5z 6 หลายเดือนก่อน +14

    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

  • @drago3393
    @drago3393 ปีที่แล้ว +71

    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 ปีที่แล้ว +8

      or else u can count number of zeros and return pow(2,n)

    • @vaibhavjaiswal7811
      @vaibhavjaiswal7811 ปีที่แล้ว +2

      Wow! This really blew my mind. So simple. Thanks

    • @yashhokte1020
      @yashhokte1020 ปีที่แล้ว +3

      Bro intuition behind it? Why we need to sort it in descending order?

    • @karthik53r35
      @karthik53r35 ปีที่แล้ว +3

      @@yashhokte1020 doing that will make all zero's behind thus considering both not pick and pick counts while adding

  • @chirlasowmyareddy
    @chirlasowmyareddy ปีที่แล้ว +21

    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 25 วันที่ผ่านมา +1

      thank you buddy

  • @tc2games176
    @tc2games176 ปีที่แล้ว +32

    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.

  • @subhajitdey135
    @subhajitdey135 5 หลายเดือนก่อน +34

    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 4 หลายเดือนก่อน +2

      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 4 หลายเดือนก่อน

      dp = [[-1 for _ in range(k + 1)] for _ in range(n + 1)]

    • @ShubhamKumar-re4zv
      @ShubhamKumar-re4zv 3 หลายเดือนก่อน

      Yes you are correct

    • @divy04
      @divy04 2 หลายเดือนก่อน

      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 2 หลายเดือนก่อน +1

      @@divy04 your trick is failing in the 48th test case

  • @anuragpandey8165
    @anuragpandey8165 2 ปีที่แล้ว +35

    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.

  • @yashgarg8921
    @yashgarg8921 5 หลายเดือนก่อน +13

    striver's love for lec-7 is unreal

    • @INTO2509
      @INTO2509 วันที่ผ่านมา

      same dp bro

  • @avneeshgoyal4554
    @avneeshgoyal4554 2 ปีที่แล้ว +24

    map can be used for storing for negative values. where key is {index,sum}

    • @rishabhgupta9846
      @rishabhgupta9846 ปีที่แล้ว +5

      can you share solution using map ,I'm getting wrong answer

    • @thomasshelby6780
      @thomasshelby6780 หลายเดือนก่อน +2

      since when map is defined like that ,it must be map mp;

  • @divyanshbalisterverma1734
    @divyanshbalisterverma1734 ปีที่แล้ว +25

    Understood, even solved without watching video.... Best DP series on any platform.💯💯💯💯💯

  • @parthsalat
    @parthsalat 2 ปีที่แล้ว +56

    *Code timestamps*
    Recursion: 15:00
    Memoization: 20:50
    Tabulation: 33:50
    *Complexities timestamps*
    Recursion: 15:40
    Memoization: 21:08

  • @indraneel6601
    @indraneel6601 2 ปีที่แล้ว +11

    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

  • @subratsahai2017
    @subratsahai2017 2 ปีที่แล้ว +7

    we can use map, understoodd

  • @aditianand6966
    @aditianand6966 10 หลายเดือนก่อน +13

    best part "lecture seven is the most important in the whole universe"

  • @manishprajapati8544
    @manishprajapati8544 2 ปีที่แล้ว +61

    I done this question without watching this video in just 26 min. My concepts are getting crystal clear thanks Raj VikramAditya 🤩🤩🤩

    • @aryankumar87771
      @aryankumar87771 ปีที่แล้ว +8

      it's not "just" 26 min, this is a 10 min problem

    • @mgfreefirelover4471
      @mgfreefirelover4471 ปีที่แล้ว

      I'm also brother do this problem without watching the video ☺️

    • @manishprajapati8544
      @manishprajapati8544 ปีที่แล้ว

      @@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 ปีที่แล้ว +1

      @Tokyo haha, bro its 1 min problem, depends on your typing speed🤭

  • @maradanikhil6882
    @maradanikhil6882 ปีที่แล้ว +31

    we can use "unordered_map" instead of vector for storing ,if there are negative numbers;

    • @Sumeet_100
      @Sumeet_100 11 หลายเดือนก่อน

      but this still gives TLE ? isn't it ?

    • @muditkhanna8164
      @muditkhanna8164 10 หลายเดือนก่อน +1

      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 10 หลายเดือนก่อน

      @@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 9 หลายเดือนก่อน

      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 20 วันที่ผ่านมา

      @@kushjoshi9427 we can use as unordered_map? isn't that correct?

  • @codermal
    @codermal 2 ปีที่แล้ว +12

    map could be used for -ve integer case and btw understood💯

    • @rishabhgupta9846
      @rishabhgupta9846 ปีที่แล้ว +4

      pls share solution using map ,I'm getting wrong answer

    • @_ANIKETVerma
      @_ANIKETVerma ปีที่แล้ว +2

      plese share the solution

  • @namansharma5128
    @namansharma5128 ปีที่แล้ว +7

    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;
    }

  • @animeshbarole
    @animeshbarole ปีที่แล้ว +4

    Understood, even solved without watching video.... Best DP series on any platform.

  • @HARSHPIPAL
    @HARSHPIPAL 2 ปีที่แล้ว +2

    sir,you can directly write single base case for recursive part (if ind==-1) if(target==0) return 1; else return 0;

  • @anishkumarde5505
    @anishkumarde5505 2 ปีที่แล้ว +27

    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 ปีที่แล้ว

      we can also use array for index and map for target (every element of indexe's array will contain map)

    • @rishabhgupta9846
      @rishabhgupta9846 ปีที่แล้ว +3

      can you share the solution using map,I'm getting wrong answer

    • @Sumeet_100
      @Sumeet_100 11 หลายเดือนก่อน

      ​@@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

  • @AshishGupta-bi4rh
    @AshishGupta-bi4rh 2 ปีที่แล้ว +17

    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 ปีที่แล้ว

      So what should be approach

    • @jeemains3524
      @jeemains3524 ปีที่แล้ว

      @@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]

  • @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.

  • @johncenakiwi
    @johncenakiwi 2 ปีที่แล้ว +9

    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.

  • @GauravKumar-wk9tr
    @GauravKumar-wk9tr 4 หลายเดือนก่อน +3

    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;
    }

  • @rahulsrivastava9710
    @rahulsrivastava9710 2 ปีที่แล้ว +9

    I did it my own...got stucked but cleared 😊 Thank you Bhaiya @Striver Bhaiya

  • @dharmeshpoladiya9047
    @dharmeshpoladiya9047 2 ปีที่แล้ว +3

    Understood 💯💯 Great Explanation. Thank you very much for all you efforts🔥🔥

  • @shivanshsingh176
    @shivanshsingh176 ปีที่แล้ว +5

    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 !!!

  • @goooo9561
    @goooo9561 ปีที่แล้ว +9

    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 5 หลายเดือนก่อน

      Thank you

  • @girishbhargava6367
    @girishbhargava6367 2 ปีที่แล้ว +28

    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 ปีที่แล้ว +3

      I also thinking same, but then in map, key will be pair and value in single int.isn't it ??

    • @rishabhgupta9846
      @rishabhgupta9846 ปีที่แล้ว

      can you share the code using map

    • @HimanshuSingh-rm5sd
      @HimanshuSingh-rm5sd 9 หลายเดือนก่อน +1

      @@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

  • @shreyasnagabhushan4918
    @shreyasnagabhushan4918 ปีที่แล้ว +2

    we can use dictionaries to store DP instead of 2D array, if negative integers are present in array .

  • @naveenvebuthi8357
    @naveenvebuthi8357 3 หลายเดือนก่อน +2

    For testcase
    num={0,0,0,0}
    tar=0
    answer should be 16,
    But code generating output as 1.

  • @piyushsaxena6243
    @piyushsaxena6243 2 ปีที่แล้ว +3

    understood , love ur explanation of each and every problem

  • @PratikPatil
    @PratikPatil ปีที่แล้ว +4

    unordered_map or map can be used to store the negative states of target

  • @theunknown1333
    @theunknown1333 ปีที่แล้ว +1

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

  • @MukeshKumar-cc3uh
    @MukeshKumar-cc3uh 4 หลายเดือนก่อน

    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 15 วันที่ผ่านมา

      can u provide the code

  • @sujayshanbhag2055
    @sujayshanbhag2055 ปีที่แล้ว +29

    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 ปีที่แล้ว

      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 ปีที่แล้ว +6

      oh bhai GFG main 4 ghante se sir phod raha tha! thanks yaar

    • @aasmohammad2651
      @aasmohammad2651 ปีที่แล้ว +1

      nice brother because i was trying to solve this problem on gfg

    • @kgdfcr2347
      @kgdfcr2347 ปีที่แล้ว

      ​@@aasmohammad2651 bro gfg pe case 104 galat aruha hai yeh logic ke baad bhi can u pls help

  • @sagarbathla5160
    @sagarbathla5160 ปีที่แล้ว +30

    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 ปีที่แล้ว +3

      watch his next lecture u will come to know about it

    • @siddhiparsekar
      @siddhiparsekar ปีที่แล้ว +4

      hey, i got the same doubt...did you get it why he started from 0 and not 1 like before?

    • @VishalKumar-yc3wr
      @VishalKumar-yc3wr ปีที่แล้ว +1

      Bhai explain kar do

    • @shreyanshpatil8303
      @shreyanshpatil8303 10 หลายเดือนก่อน

      start with 1 still it gives the correct output

  • @AlokLaha-te2pd
    @AlokLaha-te2pd 20 วันที่ผ่านมา

    Thanks Striver. Understood it very well. For negative indexes we can use map where keys will be pair of index, sum

  • @vaishnavip4808
    @vaishnavip4808 ปีที่แล้ว +2

    @takeUforward.Just a little curious, now since we have a positive values in the array.,starting the possible sum values from 0 to K suffices.If there were negative values, we don't have a bound for k.Can we still see overlapping subproblems.Ideally k could be anything from -infinity to +infinity. Would dp work in such a case.

  • @ranasauravsingh
    @ranasauravsingh 2 ปีที่แล้ว +8

    UNDERSTOOD... !
    map data structure... ? for negative input integers...
    Thanks for the video... :)

  • @adityashrivastav4983
    @adityashrivastav4983 2 ปีที่แล้ว +15

    Please provide leetcode link also

  • @harshwardhanpatki846
    @harshwardhanpatki846 ปีที่แล้ว +2

    Understood 🔥🔥🙏 thank you very much for your hard work🛐

  • @Flynn-lk8im
    @Flynn-lk8im 5 หลายเดือนก่อน +2

    ⚠ 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`.

  • @aryanrastogi1335
    @aryanrastogi1335 2 ปีที่แล้ว +3

    if sum will negative we can use map.

  • @RaghavSharma-nt3hr
    @RaghavSharma-nt3hr 2 ปีที่แล้ว +13

    NOTE:
    CASE OF- if(target==0 && arr[0]==0)
    return 2;

  • @keshavbiyani9202
    @keshavbiyani9202 19 วันที่ผ่านมา

    Thanks Striver for the lovely content man. Here's the condition needed to deal with multiple 0's in the array
    if index >= n:
    if sum == 0:
    return 1
    else:
    return 0
    Here's the complete python code
    class Solution:
    def recursive(self, arr, n, index, sum, dp):
    MOD = 1000000007

    if index >= n:
    if sum == 0:
    return 1
    else:
    return 0

    if dp[index][sum] != -1:
    return dp[index][sum]

    notPick = self.recursive(arr, n, index+1, sum, dp)
    if arr[index]>sum:
    dp[index][sum] = notPick
    else:
    pick = self.recursive(arr, n, index+1, sum-arr[index], dp)
    dp[index][sum] = (pick%MOD+notPick%MOD)%MOD

    return dp[index][sum]

    def perfectSum(self, arr, n, sum):
    # code here
    dp = [[-1 for _ in range(sum+1)] for _ in range(n)]
    return self.recursive(arr, n, 0, sum, dp)

  • @mayanksinghal9315
    @mayanksinghal9315 6 หลายเดือนก่อน +1

    For anyone facing the problem with {0, 0, 1} scenario. They can use shifting of index explained in video DP25 - LCS.

  • @mayankbharti531
    @mayankbharti531 ปีที่แล้ว +17

    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

    • @dextertim2779
      @dextertim2779 ปีที่แล้ว

      Thanks it worked😊

    • @63_bhaveshkumar71
      @63_bhaveshkumar71 ปีที่แล้ว

      yeah it worked! may u explain it?

    • @yashrawat5158
      @yashrawat5158 ปีที่แล้ว

      can you explain this?

    • @varunsharma5582
      @varunsharma5582 ปีที่แล้ว +3

      @@63_bhaveshkumar71 ​ @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.

  • @pawanharwani4598
    @pawanharwani4598 2 ปีที่แล้ว +13

    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  2 ปีที่แล้ว +6

      Thats a valid question, let mr address this in the next video.

    • @Aks-47
      @Aks-47 2 ปีที่แล้ว +4

      @@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 ปีที่แล้ว +4

      @@bharathkumar5870 first understand the question, and then cross question.. This set is different from "set" data structure

    • @shivangagrawal2923
      @shivangagrawal2923 2 ปีที่แล้ว

      @@takeUforward solution?

  • @riderpd09
    @riderpd09 2 ปีที่แล้ว

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

  • @swapnilingale4164
    @swapnilingale4164 5 หลายเดือนก่อน

    It's ok to use unorderd map

  • @Anschlusss
    @Anschlusss ปีที่แล้ว +5

    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

  • @shobhit351
    @shobhit351 2 ปีที่แล้ว +6

    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 ปีที่แล้ว

      the last code is the most optimized one

  • @divyanshusingh2396
    @divyanshusingh2396 2 ปีที่แล้ว

    I am able to do maximin problem on my own. Thank you striver

  • @divyanshbhatt8273
    @divyanshbhatt8273 4 หลายเดือนก่อน

    we can use a matrix of the size of the range of nums[i] limit + 1 if they are negative numbers and for every sum we are going to add the max limit to the sum and then return accordingly i.e dp[n-1][target + maxlimit]....

  • @anveshkarra3861
    @anveshkarra3861 2 ปีที่แล้ว +3

    i think we can use hash map for negative numbers

  • @humbleGuy_1729
    @humbleGuy_1729 2 ปีที่แล้ว +7

    We will get overlapping subproblems only when there are duplicate elements in the array (talking only for this particular problem)

    • @tanmayrauth7367
      @tanmayrauth7367 ปีที่แล้ว +1

      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 ปีที่แล้ว

      @@tanmayrauth7367 i was speaking only for this problem bro..

  • @listicle273
    @listicle273 9 หลายเดือนก่อน

    I think we can use map where key can be of type pair of int with first as index and second as target and value as the answer we might be getting inside the recursion.

  • @sumitpadadune3763
    @sumitpadadune3763 ปีที่แล้ว +1

    understood sir thanks for such great series on DP

  • @vaibhavdeshmukh7900
    @vaibhavdeshmukh7900 ปีที่แล้ว +6

    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.

  • @dishagupta7446
    @dishagupta7446 2 ปีที่แล้ว +7

    In case of negative numbers we can use hashmap

  • @karanprabhakar72
    @karanprabhakar72 2 ปีที่แล้ว +2

    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 2 ปีที่แล้ว

      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 2 ปีที่แล้ว

      @@SasukeUchiha-jb6rf pair of int and int
      First index from ( n-1 to 0) and other int represents sum formed so far

    • @karanprabhakar72
      @karanprabhakar72 2 ปีที่แล้ว

      @@SasukeUchiha-jb6rf let ne add code for it

    • @saunaknandi1814
      @saunaknandi1814 2 ปีที่แล้ว

      @@karanprabhakar72 can u send the whole code

  • @sohamnandi7526
    @sohamnandi7526 หลายเดือนก่อน +1

    "Lecture 7 is most important lecture in the entire universe" - Striver
    Me: Thala for a Reason 😅

  • @niravsingh4532
    @niravsingh4532 2 ปีที่แล้ว +5

    The linked problem is different.

  • @Steve-kv5we
    @Steve-kv5we ปีที่แล้ว +12

    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 ปีที่แล้ว +1

      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 ปีที่แล้ว +1

      @@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 ปีที่แล้ว

      @user-ht9fr8sd8u op vai

    • @romanreigns4235
      @romanreigns4235 ปีที่แล้ว

      @@rishabhgupta9846 thanks bro 😊

  • @thebibeksaha
    @thebibeksaha ปีที่แล้ว

    Map> maybe?

  • @SarvanShivani234
    @SarvanShivani234 หลายเดือนก่อน +1

    indeed taking us forward😊

  • @sunilpanchal1498
    @sunilpanchal1498 2 ปีที่แล้ว +4

    Understood, and we can use unordered_map for negative values.

    • @naamhaii
      @naamhaii 10 หลายเดือนก่อน

      unordered_map u;

  • @himanshuagrawal8012
    @himanshuagrawal8012 2 ปีที่แล้ว +18

    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.

    • @7ns3l
      @7ns3l 2 ปีที่แล้ว +7

      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 ปีที่แล้ว +1

      @@7ns3l right

    • @priyak8786
      @priyak8786 2 ปีที่แล้ว +1

      @@7ns3l yeah

    • @parthsalat
      @parthsalat 2 ปีที่แล้ว +1

      @@7ns3l Thanks for the hint

    • @ankursingh8296
      @ankursingh8296 ปีที่แล้ว

      But what will be the base case

  • @sanchitbhadgal4303
    @sanchitbhadgal4303 2 ปีที่แล้ว

    Thanks buddy, solved it with out the video and that too all codes from recursion to space optimization. Thanks alot

  • @ShahNawaz-cx3pi
    @ShahNawaz-cx3pi 27 วันที่ผ่านมา +1

    *********** Iterative Code for the count number subsequence whose sum is k ( & 0

  • @rohitraj5832
    @rohitraj5832 2 ปีที่แล้ว +17

    @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 ปีที่แล้ว

      hey. what do you mean ?

    • @ankurshahi9527
      @ankurshahi9527 ปีที่แล้ว

      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 ปีที่แล้ว +5

      @@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 ปีที่แล้ว

      @@Steve-kv5we thanks have a good understanding from this

    • @tridibeshmisra9426
      @tridibeshmisra9426 ปีที่แล้ว

      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.

  • @vanshsehgal9475
    @vanshsehgal9475 2 ปีที่แล้ว +3

    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.

  • @neptune25
    @neptune25 ปีที่แล้ว +2

    for multiple zeros change this base case
    if(nums[0]

    • @anishpatro
      @anishpatro ปีที่แล้ว

      tq bro

    • @zhunzargulhane6741
      @zhunzargulhane6741 6 หลายเดือนก่อน

      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

  • @gunduboinadileep9523
    @gunduboinadileep9523 7 หลายเดือนก่อน

    understand!!. I think maps are the data structures where we can store data with negative indices.

  • @sahilgoyals
    @sahilgoyals 2 ปีที่แล้ว +20

    map data-structure in c++ for handling -ve sum

    • @SasukeUchiha-jb6rf
      @SasukeUchiha-jb6rf 2 ปีที่แล้ว

      Hi Sahil, how can we use map for -ve sum? Can you elaborate with a example

    • @sahilgoyals
      @sahilgoyals 2 ปีที่แล้ว +7

      @@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 🙂

  • @karthikmohan79
    @karthikmohan79 2 ปีที่แล้ว +6

    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.

  • @harshit4190
    @harshit4190 2 ปีที่แล้ว

    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 2 ปีที่แล้ว

      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 2 ปีที่แล้ว

      It will be better to go with map DS to mark the sums as hinted in the video .

    • @adheeshmishra7882
      @adheeshmishra7882 2 ปีที่แล้ว +1

      @@puneetchhabra2278 take the sum of positive numbers only for dp matrix declaration...just a way around it...map suggested...

    • @puneetchhabra2278
      @puneetchhabra2278 2 ปีที่แล้ว +1

      @adheesh Mishra , extra o(n) time will be required to find the max positive sum and what if the target sum is negative

  • @tejashwinibadi9984
    @tejashwinibadi9984 ปีที่แล้ว +1

    Understood.
    I think List can be used for negative values in Java.

  • @yoginpahuja5557
    @yoginpahuja5557 2 ปีที่แล้ว +3

    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 ปีที่แล้ว

      Sort the array

    • @Steve-kv5we
      @Steve-kv5we ปีที่แล้ว

      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]

  • @AvishekChatterjee
    @AvishekChatterjee 2 ปีที่แล้ว +4

    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 ปีที่แล้ว +2

      then you cannot write tabulation method easily.

  • @srcodes13
    @srcodes13 หลายเดือนก่อน

    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.

  • @rahilsanghavi9347
    @rahilsanghavi9347 ปีที่แล้ว +2

    I have one doubt, how do we account for 0s present in the array?

  • @ratinderpalsingh5909
    @ratinderpalsingh5909 2 ปีที่แล้ว

    Understood, sir. Thank you very much.

  • @DevashishJose
    @DevashishJose 7 หลายเดือนก่อน

    understood. thank you so much

  • @himansh4812
    @himansh4812 11 หลายเดือนก่อน

    @32:00 We can use unordered map to store sum and index pair. When sum can be negative.

    • @craftanddiy4773
      @craftanddiy4773 15 วันที่ผ่านมา

      can u provide the code

  • @aruna5869
    @aruna5869 5 หลายเดือนก่อน

    understod. excellent teaching

  • @ammanchhetri6716
    @ammanchhetri6716 11 หลายเดือนก่อน

    and i think if the array can have negative indegers ..then we can caluclate the minimum sum possible of the whole array ...and shift the indexes to the right by that sum

  • @aniketpathak2721
    @aniketpathak2721 2 ปีที่แล้ว

    Understood! Hash map could be used for -ve numbers

  • @Mr.codinghacker
    @Mr.codinghacker 5 หลายเดือนก่อน +1

    congrats for 500k subscribers bhaiya

  • @hrushikesh-1914
    @hrushikesh-1914 10 หลายเดือนก่อน

    Understood. Thankyou Sir

  • @surajmisal3898
    @surajmisal3898 2 ปีที่แล้ว

    I have solved this without watching the video. Thank you very much sriver.

  • @KapilSharma56419
    @KapilSharma56419 18 วันที่ผ่านมา

    // Handling the first element of the array separately
    if (arr[0]

  • @ayushkhandelwal7178
    @ayushkhandelwal7178 2 ปีที่แล้ว

    What would be the modification if we can take any element just once?

  • @ShubhamKumar-re4zv
    @ShubhamKumar-re4zv 3 หลายเดือนก่อน +2

    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

  • @dhruvkaran9724
    @dhruvkaran9724 2 ปีที่แล้ว

    thanks striver i am able to solve DP problem on my own ... feels like apun ich bhagwan hai

  • @RitamSharmaBBB
    @RitamSharmaBBB ปีที่แล้ว +1

    In the recursive code that is given below we would only find the subsequences with sum K. because the ind is going only in one direction (n-1 to 0). however the question states "subsets". for eg. for the array {1,2,3,7,8,9} with k = 11, the given algo would find only consider the subset {7,3,1} but not {3,7,1}or {1,7,3}. then why are all the testcases passing ?

  • @SajanKumar-ec2us
    @SajanKumar-ec2us 3 หลายเดือนก่อน

    all test cases satisfying your code now

  • @prasannasippa5962
    @prasannasippa5962 2 ปีที่แล้ว

    understood thank you so much
    can anyone tell me the change we have to do for leetcode problem