DP with Bitmasking #1

Sdílet
Vložit
  • čas přidán 28. 08. 2024
  • Since we already know what bitmasking is, so let us get started with DP with bitmasking.
    Incase you want to learn about bitmasking first then you can watch: • What is Bitmasking
    I will discuss the brute force solution followed by recursive solution followed by the DP solution and then code it explaining my thought process line by line.
    Problem statement: docs.google.co...
    Solution: ideone.com/FRrbFB
    Make sure you subscribe and if need more reasons apart from the easy to understand explanation to tough concepts then you can watch: m.facebook.com...
    Enjoy watching!!
    Super useful books for algo ds and programming fundamentals!
    1. Introduction to Algorithms by Cormen: amzn.to/35AmQqu
    2. The Algorithm Design Manual: amzn.to/2K9RGPq
    3. Fundamentals of Data Structures in C++: amzn.to/2LCwIsN
    4. Object-Oriented Programming by E Balagurusamy: amzn.to/2Xxmdtr
    5. Head First Java: amzn.to/39kb44K
    6. Cracking the coding interview: amzn.to/3iDOHLK
    7. Database System concepts: amzn.to/3pisuFQ
    8. Operating Systems: amzn.to/39fcmis
    9. Discrete Mathematics: amzn.to/2MlgCE6
    10. Compiler Design: amzn.to/3pkYvx2

Komentáře • 117

  • @tarunpahuja3443
    @tarunpahuja3443 Před 2 lety +17

    You are blessed with great teaching skills. Please don't stop posting videos.

  • @anshumandas5392
    @anshumandas5392 Před 3 lety +22

    That sublime text is somehow a magical platform, everytime you make a compilation error, you open it and it magically tells you immediately what was the error in your code🤣. BTW very nice video.

    • @AlgosWithKartik
      @AlgosWithKartik  Před 3 lety +17

      Sublime sure is magical
      I open sublime and instantly it tells me the error in my code
      Top Tip for debugging your codes xD

  • @harshit4190
    @harshit4190 Před 2 lety +20

    Text Summary for Video :
    J1,J2,J3 ... Jn Jobs
    P1,P2,p3.... Pn People
    Assign Job to P1 in N ways
    Assign Job to P2 in N - 1 ways
    Assign Job to P3 in N - 2 ways
    .. so on
    Time Complexity = N * (N - 1) * (N - 2)...* 1 = O(N!)
    1. Idea - Recursion
    (CurJobToAssigned,PeopleSet) = ({1..N},{P1,P2..PN})
    (1,{P1,P2..PN})
    / \
    (2,{P2,P3..PN}) ... (2,{P1,P3...PN})

    -> Obviously This recursion would have overlapping states.
    -> Considering Each permutation as a state and storing it would be heavy storage intensive task
    -> Seeing the constraints what if we represent each permutation of set through a integer.
    2. Defining DP
    DP[i][mask] = where mask is integer representation of a permutation of a subset given.
    = Min cost of assigned given people by mask to i to N jobs remaining.
    3. Recurrence
    dp(i,mask) = MIN { for all valid j | { C(j,i) + dp(i + 1,mask with jth bit off) } }
    Time -> O(N^2 * 2^N)
    Space -> O(N * 2^N)

  • @sahilkalamkar5332
    @sahilkalamkar5332 Před 4 lety +26

    This is also known as Assignment problem in Optimization technique mathematics. Fun to see it solve with dp with bitmasking :)

    • @AlgosWithKartik
      @AlgosWithKartik  Před 4 lety +25

      Yess, infact there is an Algorithm known as Hungarian Algorithm to solve this problem which is more efficient than the DP bitmask solution.
      The Problem looked great for an introductory video on bitmask dp :)

    • @mananshah2140
      @mananshah2140 Před 3 lety +4

      @@AlgosWithKartik can you please make a video on hungarian algorithm too?

  • @introvertsinger710
    @introvertsinger710 Před 3 lety +3

    NO.1 youtube channel for CP topics...

  • @akashghosh4766
    @akashghosh4766 Před 4 lety +17

    Thanks bro for keeping my request.Keep up the good work .Will share your channel to my friends.

  • @narendramanglani4386
    @narendramanglani4386 Před 4 lety +8

    Your way of explaining things is really good, Thanks for the awesome explanation.

  • @blenderstuff7861
    @blenderstuff7861 Před 3 lety +2

    The last seconds of video was really important because i knew already that your earlier code is going to fail due to mistakes you made. I mean, everyone makes mistakes, so just chill. I am not complaining 😅☺

  • @shiv2811
    @shiv2811 Před 3 lety

    i understands your solution in 15 min...but took 20 min to think the time complexity.
    overall one of the great explanation

  • @shubhamagarwal2998
    @shubhamagarwal2998 Před 3 lety +2

    Rare + gem 💎 content .... Thanks bhaiya 👍

  • @anshumandas5392
    @anshumandas5392 Před 3 lety +6

    Really great video brother. Appreciate your teaching skills 🙌

  • @peakpotential9
    @peakpotential9 Před rokem +2

    really helpful video

  • @aabhassaxena2490
    @aabhassaxena2490 Před 4 lety +16

    Dp(i,mask) is not required coz set bits of mask = i hence i is redundant.
    Dp(mask) would do
    TC - N*2^N
    SC - 2^N

    • @AlgosWithKartik
      @AlgosWithKartik  Před 4 lety +6

      Did I not mention this anywhere in the entire video? xD
      Anyway the observation is correct :)
      Tried to keep it as beginner friendly as possible.
      Also based upon this do you think I'm correct if I establish a tighter bound on my Implementation and say that it is O(N*2^N) in the worst case?

    • @aabhassaxena2490
      @aabhassaxena2490 Před 4 lety +1

      @@AlgosWithKartik yes that is true but space would be reduced if we dont use i

  • @piyushsrivastava5883
    @piyushsrivastava5883 Před 5 měsíci

    Genuine padhaya bhaiya

  • @RAHULYADAV-zr5fq
    @RAHULYADAV-zr5fq Před 10 měsíci

    Bahut badhiya sir ❤❤

  • @sarthakgokhale7367
    @sarthakgokhale7367 Před 2 lety +1

    really good explaination skills very clear and crisp

  • @aup7125
    @aup7125 Před rokem

    Damn , such a smooth explanation ! Loved it and thank you !

  • @user-sc6uc3nl9t
    @user-sc6uc3nl9t Před 3 lety +1

    Very clear and detailed explanations!

  • @subhamjha8917
    @subhamjha8917 Před rokem

    Thanks for your help fellow DTUite!

  • @shivangraina9698
    @shivangraina9698 Před 3 lety

    Great man. I just solved a problem using this concept.. Very clear explanation. Thanks a lot

  • @akshaykumar-io5nu
    @akshaykumar-io5nu Před 3 lety +2

    really nice explanation.
    Thanks a lot

  • @deepakgupta3440
    @deepakgupta3440 Před 3 lety +1

    Tum bhut mast kaam krta hai Kartik bhai

  • @guardkaiser9344
    @guardkaiser9344 Před 3 lety +1

    Thanks a ton for the wonderful explanation...i am very grateful

  • @ronakjethava9810
    @ronakjethava9810 Před 3 lety

    It's great explanation. But I am little bit confused about time complexity.
    Claim : the number of unique states are just 2^n.
    Explanation :
    here we have two dp states, the job number and mask. But the job number is nothing but the number of off bits in mask. So, it's a redundant dp state. So, unique state is 2^n only.
    Like
    for i = 0, mas which has zero set bit is only valid mask, nC0 = 1
    For i=1, mask which has only one set bit are only valid masks, so nC1 masks
    .....
    For i=n, possible masks are nCn.
    And since 0

  • @vishal-sr5et
    @vishal-sr5et Před 10 měsíci

    Awesome series bhaiya🤩🤩

  • @vishnuvardhan623
    @vishnuvardhan623 Před 3 lety

    Thanks for the content . I like the way you explain the things.

  • @thedankest1974
    @thedankest1974 Před 2 lety

    You are brilliant at teaching!

  • @anishdatta698
    @anishdatta698 Před rokem

    Time complexity can be optimized to O(n×2^n) as given the bitmask j, we can easily find out state i as it is the number of 0s + 1, hence we won't need a 2D dp.

  • @akhilhooda740
    @akhilhooda740 Před 3 lety +1

    best series!!!

  • @ImSaneperson
    @ImSaneperson Před 3 lety +1

    Nice one ... enjoyed learning this part.

  • @ekanshsharma1309
    @ekanshsharma1309 Před 7 měsíci

    Thank you so much sir.... Awesome explaination😄

  • @ayushjain737
    @ayushjain737 Před 3 lety +1

    Very well explained!

  • @kousthubhtadanki1237
    @kousthubhtadanki1237 Před 2 lety

    super super super....awsm explanation!!!!

  • @RAMSINGH-kt3wk
    @RAMSINGH-kt3wk Před 4 lety

    bro once again thanks for such a beautiful lecture

  • @padmavathi4068
    @padmavathi4068 Před 3 lety +1

    Really a valuable content

  • @palashrathore6277
    @palashrathore6277 Před 3 lety +2

    Helpful, Thanks!

  • @nasimnajand9697
    @nasimnajand9697 Před měsícem

    this video was greatfuly helpful sir, thanks in advance. Is it possible for you to make video about number of wonderful substring problem from leetcode please ?

  • @varsha4260
    @varsha4260 Před 3 lety +6

    Thanks bro but I have a doubt here,since the paths will always be unique so I think dp[mask] is enough instead of dp[state][mask],right?

    • @AlgosWithKartik
      @AlgosWithKartik  Před 3 lety +5

      by using the number of set/unset bits in the mask we can uniquely identify the correct value for 'state'.
      So yes you are correct 'state' here is redundant and we can have solution with/with-out it.

    • @varsha4260
      @varsha4260 Před 3 lety +4

      @@AlgosWithKartik thank you so much for your instant reply bro,a lot of youtubers don't reply to our doubts but you are awesome bro.Thank you so much once again.

  • @usmanusmonov2340
    @usmanusmonov2340 Před 3 lety +1

    Good explanation!

  • @puneethsaladi5499
    @puneethsaladi5499 Před 2 lety

    Really good explanation!

  • @sfechisalin
    @sfechisalin Před 4 lety +4

    Hi Kartik,
    I've seen your video on calculating the time and space complexity for dp problems but i'm not fully convinced that the final time complexity is O(N^2 x 2^N).
    As you mentioned in your video: Time complexity = Number of states * Transition Time.
    I can agree with you that we have 2 ^ N states. But I don't understand why the transition time is N ^ 2. In this video you said N ^ 2 because we're matching every person with every job but ( i think you referred here to the c[ j][i] but for a state i we only try to match the n works that we have to solve the task i. For me it looks more like the transition time is N and the final time complexity is O(N x 2 ^ N). I may be wrong here so please correct me.

    • @AlgosWithKartik
      @AlgosWithKartik  Před 4 lety +17

      Time complexity is O(N^2*2^N).
      I might have messed up while saying that the transition time is O(N^2), it is not it is O(N), sorry about that.
      Here is the analysis:
      1. Number of states = N*2^N.
      2. Per state I look at N other states(refer to the for loop inside solve())
      3. This gives me a transition time of O(N).
      4. Overall = N*N*2^N
      Let me know if this helps :)

    • @sfechisalin
      @sfechisalin Před 4 lety +2

      @@AlgosWithKartik , thanks, it's clear now :)

  • @apoorvajain9196
    @apoorvajain9196 Před 4 lety +1

    Nice explanation 👍

  • @ronakslibrary8635
    @ronakslibrary8635 Před rokem

    Nice Explanation bro 👍👍

  • @barradas5591
    @barradas5591 Před 3 měsíci

    THANK YOU A LOT

  • @mr.twinklesharma5826
    @mr.twinklesharma5826 Před 3 lety

    Thanks sir, Really good explanation.

  • @adityagirishpawate1465
    @adityagirishpawate1465 Před 3 lety +1

    great video

  • @suprabhatkumar151
    @suprabhatkumar151 Před 4 lety +1

    2^n is for permutation of jobs that will be assigned to people or permutation of people who will be assigned jobs?

  • @devkaran25
    @devkaran25 Před 2 lety

    thanks for teaching this topic :-)

  • @vijaykumarlokhande1607

    You can also use the code editor of dark theme/background. Everything else is 'Perfect'.

  • @tanmaychandra9434
    @tanmaychandra9434 Před 2 lety

    Kartik, Time Complexity of your code here is O(N^2) right ? Because we are not iterating through every possible-mask here. We are just seeing for jobs [0, n) if they are set in mask or not which O(N) * recursion Time O(N) again. Please do correct me if I am wrong.

  • @pradhansaini5491
    @pradhansaini5491 Před 3 lety

    great explanation

  • @harshanarayana6937
    @harshanarayana6937 Před 2 lety

    good explaination.

  • @itsmyshow7611
    @itsmyshow7611 Před 3 lety +1

    Wow it is good.

  • @ParthTagalpallewar
    @ParthTagalpallewar Před měsícem

    can we relate this problem with N-Queens problem?

  • @AnchitBhardwaj
    @AnchitBhardwaj Před 3 lety

    Bro, very nice explanation. Can you tell me if we want to find that subset which has minimum value, how can we do that ?

  • @VikramKumar-tk6wg
    @VikramKumar-tk6wg Před 4 lety +2

    Bhaiya Codeforces ki problems krwa do dp with bitmasking prr bhot help ho jayegi

    • @AlgosWithKartik
      @AlgosWithKartik  Před 4 lety +6

      Bilkul bro codeforces ki R1800 se R2200 ki range me problems cover krrunga bitmasking ki.
      For now yeh choose krri as an introductory problem.

  • @twenty831
    @twenty831 Před 2 lety +1

    Is there a OJ so I can submit this problem ?

  • @rimol6221
    @rimol6221 Před 2 lety

    Why memset(dp,-1,sizeof dp);
    and why not this one memset(dp,0,sizeof dp);?
    and why you used it in locally ?
    i used int dp[21][1

  • @kento8453
    @kento8453 Před 6 měsíci

    Instead of mask, why don’t we just use a regular integer here? Masking made it a bit complicated isn’t it

  • @mohamedarshathn7768
    @mohamedarshathn7768 Před 4 lety

    Really helpful

  • @BhupendraYadav-li4ts
    @BhupendraYadav-li4ts Před 4 lety +1

    Thanks for the great solution. But imo it wasn't at all hard, bcz i have seen lot more hard questions asked by Google.

    • @AlgosWithKartik
      @AlgosWithKartik  Před 4 lety +6

      Actually the motive wasn't to solve a hard Problem but to have an introductory problem for dp bitmask.
      Hopefully down the line the difficulties will increase :)

  • @anujparashar3986
    @anujparashar3986 Před 11 měsíci

    suggest platforms also where we can submit the problems

  • @diptoacharjee7538
    @diptoacharjee7538 Před 3 měsíci

    Thanks, but can anyone provide this problem on an online judge?

  • @saurabhgupta1595
    @saurabhgupta1595 Před 3 lety +1

    Thanks sir

  • @HarpreetSingh-hi6wb
    @HarpreetSingh-hi6wb Před 3 lety +1

    thanks sir

  • @sunnychaturvedi9958
    @sunnychaturvedi9958 Před 3 lety

    One of your states is redundant , it can be calculated by no. Of set bits in mask

  • @adarshkumar1674
    @adarshkumar1674 Před 6 měsíci

    how to write the iterative version of it ??

  • @campgod2758
    @campgod2758 Před 3 lety

    nice explanation ..:)

  • @gentleman7060
    @gentleman7060 Před rokem

    time complexity should be eloborated more. if you are making the videos for redcoders then you should mention in the playlists.

  • @AmitSingh-cs2hb
    @AmitSingh-cs2hb Před 4 lety +1

    Hi bro,from where i can practice dp problems? I just completed dp section on cses.

    • @AlgosWithKartik
      @AlgosWithKartik  Před 4 lety +1

      Try Atcoder educational dp contest, spoj, codeforces

  • @devilronak7262
    @devilronak7262 Před 3 lety

    i guess in for loop it should be C[i][j] nor C[j][i], plz thell me if i am wrong and why

  • @sahazeerks2363
    @sahazeerks2363 Před 4 lety

    Sir please add more videos on bitmasking.

  • @gurharpartapdhaliwal3087
    @gurharpartapdhaliwal3087 Před 3 lety +2

    In cf u preferred top dowm or botm up?

    • @AlgosWithKartik
      @AlgosWithKartik  Před 3 lety +1

      Whichever I can code in less time.

    • @gurharpartapdhaliwal3087
      @gurharpartapdhaliwal3087 Před 3 lety +2

      @@AlgosWithKartik like top down is always easier to think but on the other hand most of the CM's,Mastrs do bottom up. Is using memorization a bad practice? Do companies ask both approaches?

    • @ayushraj-zb6sv
      @ayushraj-zb6sv Před 3 lety

      @@AlgosWithKartik Even i have the same doubt..i am able to dp problems in top down manner ..but face difficulty in bottom up.

  • @mevam123
    @mevam123 Před 3 lety

    What is the problem no for this question on leetcode or any similar question?

  • @gopal7338
    @gopal7338 Před 4 lety

    Nice!

  • @dhayalanm2206
    @dhayalanm2206 Před 3 lety +3

    Iam learning this in my 1st semester of college.(iam comfortable with what I have learnt). Am I going in right path sir....?kindly reply sir...

    • @AlgosWithKartik
      @AlgosWithKartik  Před 3 lety

      Yes you are!
      I hope you have a bright future ahead keep going :)

  • @hastishiri7538
    @hastishiri7538 Před 3 lety +2

    Sir please enable caption

  • @utkarshgupta2909
    @utkarshgupta2909 Před 3 měsíci

    Please Please answer this. If we set the ith bit in mask saying the job is taken but also after recursion undo (backtrack) and store to dp matrix (memorization) would it be ok ?
    // mask initially worker = n-1 , (i

  • @AkashRaj-ib6wz
    @AkashRaj-ib6wz Před 3 lety

    Isn't this similar to knapsack 🤔

  • @ManishGupta0070
    @ManishGupta0070 Před 4 lety

    sir,how did you add paint for sublime text

  • @tle964
    @tle964 Před 4 lety +1

    It's been 2 days...no videos?..we are waiting

    • @AlgosWithKartik
      @AlgosWithKartik  Před 4 lety +2

      Was out with friends, now I'm back on work!
      Expect videos soon and do share the channel with other people who might find it helpful!

    • @tle964
      @tle964 Před 4 lety

      @@AlgosWithKartik definitely

  • @Aysh_Sach_16-2
    @Aysh_Sach_16-2 Před 4 lety +1

    Kaha ki problem hai ye?

    • @AlgosWithKartik
      @AlgosWithKartik  Před 4 lety +1

      Common problem h bro kaafi, assignment problem kehte hain isko.
      University me padhatey hain Hungarian Algorithm.
      I thought dp with bitmask samjhane ke liye achhi rahegi.

    • @Aysh_Sach_16-2
      @Aysh_Sach_16-2 Před 4 lety

      @@AlgosWithKartik Great bhai..Thxx

  • @vaalarivan_p
    @vaalarivan_p Před rokem

    trats: 5:35

  • @gentleman7060
    @gentleman7060 Před rokem

    time complexity can be hard to someone and you have said it in 5 seconds. why dont try to eloborate more ?

  • @prithushukla8634
    @prithushukla8634 Před 7 měsíci

    Is this soln correct
    int solve(vector &cost, vector &vis, int col)
    {
    if (col == cost.size())
    return 0;
    else {
    int ans = INT_MAX;
    for (int i = 0; i < cost.size(); i++) {
    if (!vis[i]) {
    vis[i] = 1;
    ans = min(ans, cost[i][col] + solve(cost, vis, col + 1));
    vis[i] = 0;
    }
    }
    return ans;
    }
    }
    int main()
    {
    int N;
    cin >> N;
    vector cost(N, vector(N, 0));
    for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
    cin >> cost[i][j];
    }
    }
    vector vis(N, 0);
    cout