Minimum path sum | Min cost Path | Dynamic programming | Leetcode #64

Поделиться
HTML-код
  • Опубликовано: 19 окт 2024
  • This video explains a very important programming interview question which is to find minimum cost path or minimum path sum. I have shown backtracking method along with memoization optimization and finally explained the most optimal dynamic programming solution using proper example. Finally, i have explained the DP code and CODE LINK is present below. This is the 64th number question from LEETCODE. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    CODE LINK: gist.github.co...

Комментарии • 234

  • @codestorywithMIK
    @codestorywithMIK 4 года назад +197

    Explaining things like "Why won't Greedy work here", then going from "recursive" approach to optimized DP approach. This is how everyone wants to see a problem and this is how everyone should look at a problem. Start from worst and make improvements step by step. This makes your teaching style special. Thanks

  • @ronaldabellano5643
    @ronaldabellano5643 4 года назад +30

    The best. I like the use of colors that made it easy to follow.

  • @genvalencia1740
    @genvalencia1740 4 года назад +9

    I come here whenever I start to feel anxious about my solution not panning out, and I'm solving in Python. :) Thanks again for these walk-throughs, they really help. =D

  • @alfredomora5555
    @alfredomora5555 3 года назад +6

    I just had an assessment wish I saw this video earlier. The question was very similar. I appreciate your content thank you!

  • @CostaKazistov
    @CostaKazistov 2 года назад +1

    Clearest explanation of 3 different approaches to solving Minimum Path Sum problem 💯

  • @PiyushKumar-ey7qw
    @PiyushKumar-ey7qw 4 года назад +7

    memoization approach did work like a charm, instead of a 2D array, I have used unordered_map where key was a pair of i,j value.
    It got accepted.

  • @Noizept
    @Noizept 4 года назад +4

    The best video i found so far to explain this problem.

  • @zelo_s6707
    @zelo_s6707 2 года назад +1

    Thanks for this approach! Using the greedy and recursive approaches helped me understand why one would use the DP method. Nothing else made sense up until now. Keep it up!

  • @indsonusharma
    @indsonusharma 4 года назад +4

    i did by marking technique (iterative) like if you have not encountered then add that state and mark it but if you have encountered that (check by using mark 2d array )state before then take minimum of previous and current state(bit mathematical) that also lead me to AC but thanks for this beautiful approach bro! today the base case could'nt stop us in the first go lol!!

    • @techdose4u
      @techdose4u  4 года назад

      This concept is same as memoization. Today I already wrote the base case 🤣

  • @anushreegupta5830
    @anushreegupta5830 2 года назад +2

    Hats off to your teaching style! Legit the best explaination.

  • @ismail8973
    @ismail8973 3 года назад

    Explanation for Why greedy algorithm doesn't work was top notch. people usually doesn't try to think or explain in that angle. Thanks

  • @dileepkumar-nd1fo
    @dileepkumar-nd1fo 3 года назад +3

    You are mastered in explaining the things man.
    Such a neat explanation with clear voice and the colour combination will make us remember easy.

  • @techwithlord
    @techwithlord 2 года назад +1

    This is a best ever video I have ever seen from this only one video I clearly understand the GREEDY, RECURSION AND BACKTRACKING also hats off dude to your work

  • @HimanshuKumar-sl6ud
    @HimanshuKumar-sl6ud 3 года назад +3

    the way you explain complex things in easy way is awesome. please make more problems solution of leetcode .

  • @khan.mansoor
    @khan.mansoor 3 года назад +1

    You explain both problem and solutions very well. Commenting for expressing gratitude as well to offer support. Please keep up the good work.

  • @simon7671
    @simon7671 3 года назад +3

    you help me a lot! I am a beginnner and this question is just too hard for me. After watching your video, i am able to finish a similar question by myself!

  • @debaratighatak2211
    @debaratighatak2211 3 года назад +4

    Another amazing explanation, I can't really thank you enough sir! I :) The bright colours in the video really helps a lot too

  • @HariPrasad-ox5ri
    @HariPrasad-ox5ri Год назад +1

    Thank you for the simple and elegant explanation!

  • @ayoubdkhissi
    @ayoubdkhissi 3 года назад +3

    this explanation couldn't be better!! thanks

  • @peter-eh2oq
    @peter-eh2oq 2 года назад

    Thanks! Please keep going!!! Thanks soooooooooo much!!! I saw a lot of vedio about this question, you have the best explination.

  • @prathamkesarkar
    @prathamkesarkar 3 года назад +1

    As usual sir I was able to solve this within minutes with your explanation.

  • @prafulparashar9849
    @prafulparashar9849 2 года назад

    Great explanation !!
    The steps which we followed were the exact steps and approaches which came to my mind while looking at this problem for the very first time.
    I was able to go till recursion(backtracking) approach but could not figure out the last one.
    Thanks !! This was helpful.

  • @AltafHussain-on2oe
    @AltafHussain-on2oe 3 года назад +2

    I am falling in love with your Explanation 💖

  • @programmingstuff5741
    @programmingstuff5741 4 года назад +6

    Can you post the solutions of Google kickstart Round A and Round B
    These are the such good problems to practice

  • @Dizzydizzydizzy7
    @Dizzydizzydizzy7 2 года назад

    Literally best explaination on youtube

  • @utkarsh5165
    @utkarsh5165 Год назад

    Wonderful Explanation BY Tech Dost.. (Dosh)

  • @alancabrera7116
    @alancabrera7116 4 года назад +1

    iiuc, the space complexity is O(n). One only needs one vector for the running minimums.

    • @techdose4u
      @techdose4u  4 года назад +1

      True. 2 maintaining 2 rows is sufficient. This is true for most table type DP programs.

  • @Rasheed21
    @Rasheed21 23 дня назад

    That's incorrect at 7:18; memoization significantly improves time. For a 15x16 grid I was able to reduce recursive calls from 445,962,869 to 479 where there were 209 cache hits. The time dropped from 1347 ms to 1ms. That's a 1347 times improvement on time and nearly 100,000 times improvement on recursive calls. This was with Java using a 2D array for the cache (i.e. memoization) instead of HashMap. The time spent filling the array with -1's had little impact. Using HashMap also had good time of 7 ms with the same improved numbers for recursive calls and cache hits.

  • @fussycat2798
    @fussycat2798 3 года назад +1

    Nicely explained the concept. Really like it. I was able to solve the similar problems in less time. Thanks a lot for the detailed explanation

  • @DrJavyMartinez
    @DrJavyMartinez 3 года назад +1

    Dude! Your accent is tough, but after watching your video, I feel EXTREMELY comfortable applying minimum and maximum cost sum traversal algorithms through graphs!!

    • @techdose4u
      @techdose4u  3 года назад +1

      Great :) Sorry for this accent though 😅

  • @amansarma417
    @amansarma417 4 года назад +6

    i did without the dp vector. Since we could just perform modifications on the same given grid matrix.
    Space Complexity O(1) :) . I submitted that way

    • @techdose4u
      @techdose4u  4 года назад +1

      Pleas share your code.

  • @paragroy5359
    @paragroy5359 3 года назад +1

    Nice explanation sir....but instead of taking an additional dp vector if we do changes in the given grid vector only then it will be o(1) space solution

  • @rishabhgoyal8110
    @rishabhgoyal8110 4 года назад +4

    I hope this channel reaches 1m soon!

    • @techdose4u
      @techdose4u  4 года назад +2

      Thanks for your support 😀

    • @Daniel_WR_Hart
      @Daniel_WR_Hart 3 года назад

      LeetCode only has a bit over 200K users with a contest ranking, so that might take a while

  • @PriyanshuKumar-om8np
    @PriyanshuKumar-om8np 2 года назад

    The best explanation I have ever seen.

  • @kercat89
    @kercat89 4 года назад +2

    It's so easy to understand and I loved the break down from the simple to sophisticated approach!
    I have a question re the recursive solution - why is the complexity O(2^n) and not O(2^(m*n))? if it means that there's 2 options to about each cell..? Thank you

    • @techdose4u
      @techdose4u  4 года назад +3

      Thanks. Actually our number of steps will always be (m+n) from top left to bottom right. So, you can say time will be 2^(m+n).

    • @kercat89
      @kercat89 4 года назад +1

      @@techdose4u That makes sense. Thank you!

  • @prashantagrawal1140
    @prashantagrawal1140 2 года назад +1

    Brilliant Explaintion techdose

  • @ambujverma9287
    @ambujverma9287 4 года назад +1

    the way you explain things is phenomenal...
    thanks a lot

    • @techdose4u
      @techdose4u  4 года назад

      Welcome :)

    • @ambujverma9287
      @ambujverma9287 4 года назад +1

      @@techdose4u bhai you work in any MNC or u study in college(iit?)

    • @techdose4u
      @techdose4u  4 года назад

      MNC....

    • @ambujverma9287
      @ambujverma9287 4 года назад

      @@techdose4u which one.. if you don't mind brother 😅

  • @Safar_Ayushi_Ka
    @Safar_Ayushi_Ka 4 года назад +2

    Your videos are amazing plz do make more videos on DP ,it would be grateful Thanks

  • @UJJWALGIRIRA
    @UJJWALGIRIRA 2 года назад

    bhai op zeher explaination🔥🔥🔥🔥🔥🔥🔥

  • @neharikakhera6411
    @neharikakhera6411 4 года назад +3

    Thank you so much for great explanation!!

  • @viralmehta2542
    @viralmehta2542 3 года назад +2

    Nice video. Covered various approaches here.

  • @shivanij3725
    @shivanij3725 4 года назад +2

    nice explanation about dp table.Thanks

  • @shapedsilver3689
    @shapedsilver3689 3 года назад +3

    When he started getting into why greedy algorithms won't work I knew this was legit

  • @AnshumanSharmadev
    @AnshumanSharmadev 4 года назад +2

    Amazing!! You made it look so simple! Liked and Subscribed!

  • @InsightWeaver
    @InsightWeaver 2 года назад

    Amazing video mate! explained thoroughly. Cheers

  • @kumaraakash25
    @kumaraakash25 2 года назад

    Amazing explanation but why would anyone go with the DP approach if complexity is the same in both recursion and DP both

  • @pradeepvdeepu4768
    @pradeepvdeepu4768 3 года назад +2

    awesome explanation and smooth ..... ! thanks a lot

  • @sarathgovind.k.k7951
    @sarathgovind.k.k7951 3 года назад +2

    very good explanation

  • @rahulbhangale4656
    @rahulbhangale4656 3 года назад

    greedy works if you properly define dp table. dp[i][j] denotes minimum path sum from (1,1) to (i,j)

  • @OP-yw3ws
    @OP-yw3ws Год назад

    Amazing you solved all my doubts

  • @jeromealve6321
    @jeromealve6321 3 года назад +3

    I wish this video came out 3 years ago when I took my algorithms class lol

  • @wilfredomartel7781
    @wilfredomartel7781 2 года назад +1

    Great!

  • @sarvagyaiitmadras8727
    @sarvagyaiitmadras8727 3 года назад +1

    if all 4 direction mvement would be allowed then what would be changes, will changes work in it, or completenew approach would be needed ???

  • @openworld7585
    @openworld7585 4 года назад +1

    Thank you for awesome explanations of dp table

  • @shivanggupta5421
    @shivanggupta5421 4 года назад

    def findPath(x:int,y:int):
    if(x= len(grid) or y=len(grid[0])):
    return
    right = findPath(x,y+1)
    down = findPath(x+1,y)
    return min(right,down)+grid[x][y]
    I used this method. I know you said recursive method won't work but I tried for my satisfaction. But when compiling it gives error because it isn't able to compare right and left when the boundary check returns null. Can you tell me where am I wrong

  • @ABHISHEK-fy1in
    @ABHISHEK-fy1in 4 года назад +1

    Very well explained. 👌

  • @nabidhasan9548
    @nabidhasan9548 2 года назад +1

    Great explanation brother

  • @programmingstuff5741
    @programmingstuff5741 4 года назад +1

    Can you post videos on segment tree??
    Which is very useful for the purpose of comptetive programming

    • @techdose4u
      @techdose4u  4 года назад

      Already done. Search in videos.

  • @amitavamozumder73
    @amitavamozumder73 3 года назад +1

    we can also do dijksta here right? the value in each cell can be the edge weight, which is pretty close to the dp solution.

    • @techdose4u
      @techdose4u  3 года назад +1

      You can

    • @amitavamozumder73
      @amitavamozumder73 3 года назад

      @@techdose4u can you please make a video on myers diff algorithm, (the one used in github file diff), it's not anywhere in youtube,

  • @shaileshhegde9205
    @shaileshhegde9205 4 года назад

    The recursive way is DFS right with directions of right and below

  • @lemax2980
    @lemax2980 4 года назад +3

    Great sir, as usual😋

  • @tekbssync5727
    @tekbssync5727 3 года назад +4

    What a color combination and style of *Leet code* in the thumbnail ? !!!! 😂

  • @lashalezhava2313
    @lashalezhava2313 4 года назад +2

    Thanks, you explain very well :)

  • @shreelakshmi6890
    @shreelakshmi6890 2 года назад

    Great Explanation!

  • @miltonrodrigues8417
    @miltonrodrigues8417 3 года назад +1

    Good Explanation!

  • @anandakrishnan2685
    @anandakrishnan2685 3 года назад

    Nice explanation, thanks!

  • @chetanpatteparapu7600
    @chetanpatteparapu7600 4 года назад +2

    Top Down approach using backtracking and memoization:
    private int[][] memo;
    public int minPathSum(int[][] grid) {
    if (grid.length < 1)
    return 0;
    this.memo = new int[grid.length][grid[0].length];
    for (int[] row : memo)
    Arrays.fill(row, Integer.MAX_VALUE);
    return getMinPathSum(grid, 0, 0);
    }
    private int getMinPathSum(int[][] grid, int row, int column) {
    int currentValue = grid[row][column];
    if (memo[row][column] != Integer.MAX_VALUE)
    return memo[row][column];
    else if (row == grid.length - 1 && column == grid[row].length -1)
    return currentValue;
    else if (row == grid.length - 1)
    currentValue += getMinPathSum(grid, row, column + 1);
    else if (column == grid[row].length - 1)
    currentValue += getMinPathSum(grid, row + 1, column);
    else
    currentValue += Math.min(getMinPathSum(grid, row, column + 1), getMinPathSum(grid, row + 1, column));
    memo[row][column] = currentValue;
    return currentValue;
    }

  • @chelseaip759
    @chelseaip759 3 года назад +1

    THE BEST TUTORIAL

  • @jameskurakula8560
    @jameskurakula8560 3 года назад

    @7:38
    grid[I][j]+ min( dp[ i-1][j], dp[I][j-1]) , there it was j-2.

  • @ritikgandhi3605
    @ritikgandhi3605 4 года назад +2

    In line 11 of the code ,why did we initialize cols as
    int cols=grid[0].size() and not just as grid.size()?

    • @techdose4u
      @techdose4u  4 года назад +1

      Because the number of cols are same in each row and grid[O] means no of cols. Grid.size means no of rows because it is a 2D matrix.

  • @Somethingsomethinglol
    @Somethingsomethinglol 3 года назад +2

    Excellent!

  • @veereshr
    @veereshr 3 года назад +1

    if we can change the input matrix, we can use the same right? memory optimisation?

    • @techdose4u
      @techdose4u  3 года назад

      Yes if the array is mutable

  • @blume0f
    @blume0f 4 года назад +5

    awesome sir

  • @akanshagautam9815
    @akanshagautam9815 4 года назад +3

    If we can move up, down, left, and right then what changes do we have to make in the code?

    • @techdose4u
      @techdose4u  4 года назад +4

      Maybe try with Dijkstra graph algorithm.

    • @harshitchoukse2602
      @harshitchoukse2602 3 года назад

      Then you need track the path with visited array in order to bypass the cycle.

  • @mahipalsingh-yo4jt
    @mahipalsingh-yo4jt 4 года назад +1

    great video sir...........:)

  • @moonbrush5
    @moonbrush5 2 года назад

    I am stuck with a similar problem which is finding shortest path in 2D matrix from source to target which given in the problem and I have to return all i,j coordinates of the shortest path only. Please help.

  • @shyamprakashm6325
    @shyamprakashm6325 4 года назад

    How do we print the minimum path index in the given input matrix?
    Ex:(0,0)--->(0,1)--->. Some what like this...
    The same problem I have been facing when ever I use the dp concept example print the subset which has the sum=k here I could find the sum but I don't know how to find the subset...
    Please help sir

  • @aneeshmv8201
    @aneeshmv8201 4 года назад +1

    Memoization of recursive code to remove overlapping sub problem calls, will give O(N*N ) right?

    • @techdose4u
      @techdose4u  4 года назад

      It will depend on no of repeating subproblems. Actually 2^N is a much larger upper bound due to the constraint in movement. But yes, memoization should give approx N^2. But since we are still doing recursion, actual runtime can go much higher than table method if you get large matrix. So, table method is best for larger cases. I hope you got it :)

  • @harifrahman8054
    @harifrahman8054 4 года назад +1

    Nice Explanation

  • @pallabghosh3840
    @pallabghosh3840 2 года назад

    can i say the time will be in recursive approach 2^(m*n) in worst case? so we use dp for n^2 time

  • @vedant9887626061
    @vedant9887626061 4 года назад +1

    What will be the boundary conditions for recursive approach

  • @subratarudra2745
    @subratarudra2745 Год назад

    Nice explanation sir

  • @jaredmomanyi8178
    @jaredmomanyi8178 Год назад

    works like magic

  • @LovelyMountainGoat-rd7qy
    @LovelyMountainGoat-rd7qy 9 месяцев назад

    Thank you😇

  • @dhruvgoel25
    @dhruvgoel25 4 года назад

    Can you please explain me why we initialize dp like dis
    dp(row, vector(cols,0))
    The first parameter is clear bt second I couldn't get

    • @jigarmav335
      @jigarmav335 4 года назад

      dp(row , vector(cols,0)) .Here 1st parameter indicates that we want a vector of size row. Second parameter indicates that each element in our vector is a vector of size cols and is initialized to zero.
      for dp(2,vector(2,0)) it would look like this.
      {
      { 0, 0 },
      { 0 , 0 }
      }

  • @mohammedsadiq1567
    @mohammedsadiq1567 4 года назад +2

    Awesome bro!!

  • @jatinshrivastava4231
    @jatinshrivastava4231 3 года назад

    What should I do if i also have to count the number of paths through which We can reach the minimum cost as there can be more than one such paths?

  • @raj.saurabhh
    @raj.saurabhh 3 года назад

    Can we not use the extra space and use the given table for dp? I mean my testcase is ok but when i submit one solution is wrong

  • @rushabhlegion2560
    @rushabhlegion2560 Год назад

    What is that Fast I/O in C++ line at the top? Is it necessary?

  • @praveennandham2933
    @praveennandham2933 4 года назад

    can we change the same logic ass required
    when soure and destination or given??

  • @lifestoriesfromearth6271
    @lifestoriesfromearth6271 3 года назад

    which tool are you using for whiteboard

  • @alnaifmilon5420
    @alnaifmilon5420 3 года назад +1

    Thank you

  • @bigbird0617
    @bigbird0617 3 года назад

    the time complexity should be O(n*m) not O(n2) ?

  • @kbhargavi4400
    @kbhargavi4400 4 года назад +2

    TQ bro!😃

  • @alexsparrow8614
    @alexsparrow8614 4 года назад +1

    can you tell boundary check condition in recursive Method.....

    • @techdose4u
      @techdose4u  4 года назад

      Out of bounds. Reaching the desired cell. Reject higher cost path (if using memoization).

  • @RahulKumar-qu1if
    @RahulKumar-qu1if 4 года назад +1

    Thank you!🔥

  • @mohitsoni3446
    @mohitsoni3446 4 года назад +1

    awesome

  • @abdelrhmansayed340
    @abdelrhmansayed340 Год назад +1

    thanks

  • @InsightWeaver
    @InsightWeaver 2 года назад

    @tech dose what if add diagonal movement to it? how would we solve it then?

  • @yashgoswami5374
    @yashgoswami5374 4 года назад

    What will be the solution if we allow to move in all 4 directions?