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

Sdílet
Vložit
  • čas přidán 17. 04. 2020
  • 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.com/SuryaPratapK/...

Komentáře • 233

  • @codestorywithMIK
    @codestorywithMIK Před 4 lety +193

    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

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

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

  • @zelo_s6707
    @zelo_s6707 Před 2 lety +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!

  • @anushreegupta5830
    @anushreegupta5830 Před rokem +2

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

  • @ronaldabellano5643
    @ronaldabellano5643 Před 4 lety +30

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

  • @ismail8973
    @ismail8973 Před 3 lety

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

  • @khan.mansoor
    @khan.mansoor Před 3 lety +1

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

  • @peter-eh2oq
    @peter-eh2oq Před 2 lety

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

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

    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

  • @prafulparashar9849
    @prafulparashar9849 Před 2 lety

    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.

  • @Dizzydizzydizzy7
    @Dizzydizzydizzy7 Před rokem

    Literally best explaination on youtube

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

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

  • @PriyanshuKumar-om8np
    @PriyanshuKumar-om8np Před 2 lety

    The best explanation I have ever seen.

  • @fussycat2798
    @fussycat2798 Před 3 lety +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

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

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

  • @alfredomora5555
    @alfredomora5555 Před 2 lety +6

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

  • @InsightWeaver
    @InsightWeaver Před 2 lety

    Amazing video mate! explained thoroughly. Cheers

  • @UJJWALGIRIRA
    @UJJWALGIRIRA Před 2 lety

    bhai op zeher explaination🔥🔥🔥🔥🔥🔥🔥

  • @techwithlord
    @techwithlord Před 2 lety +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

  • @dileepkumar-nd1fo
    @dileepkumar-nd1fo Před 3 lety +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.

  • @utkarsh5165
    @utkarsh5165 Před 10 měsíci

    Wonderful Explanation BY Tech Dost.. (Dosh)

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

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

  • @OP-yw3ws
    @OP-yw3ws Před 11 měsíci

    Amazing you solved all my doubts

  • @HariPrasad-ox5ri
    @HariPrasad-ox5ri Před rokem +1

    Thank you for the simple and elegant explanation!

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

    Thank you so much for great explanation!!

  • @shreelakshmi6890
    @shreelakshmi6890 Před 2 lety

    Great Explanation!

  • @ABHISHEK-fy1in
    @ABHISHEK-fy1in Před 4 lety +1

    Very well explained. 👌

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

    this explanation couldn't be better!! thanks

  • @HimanshuKumar-sl6ud
    @HimanshuKumar-sl6ud Před 2 lety +3

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

  • @simon7671
    @simon7671 Před 3 lety +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!

  • @indsonusharma
    @indsonusharma Před 4 lety +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  Před 4 lety

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

  • @AltafHussain-on2oe
    @AltafHussain-on2oe Před 3 lety +2

    I am falling in love with your Explanation 💖

  • @PiyushKumar-ey7qw
    @PiyushKumar-ey7qw Před 4 lety +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.

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

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

  • @anandakrishnan2685
    @anandakrishnan2685 Před 2 lety

    Nice explanation, thanks!

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

    Thank you for awesome explanations of dp table

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

    Thanks, you explain very well :)

  • @wilfredomartel7781
    @wilfredomartel7781 Před rokem +1

    Great!

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

    Nice video. Covered various approaches here.

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

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

  • @imuksd
    @imuksd Před 3 lety

    Good Explanations!!

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

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

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

    Brilliant Explaintion techdose

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

    nice explanation about dp table.Thanks

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

    I hope this channel reaches 1m soon!

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

      Thanks for your support 😀

    • @Daniel_WR_Hart
      @Daniel_WR_Hart Před 2 lety

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

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

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

  • @whiskerAndPetal
    @whiskerAndPetal Před 2 lety

    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.

  • @DrJavyMartinez
    @DrJavyMartinez Před 2 lety +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  Před 2 lety +1

      Great :) Sorry for this accent though 😅

  • @praveennandham2933
    @praveennandham2933 Před 3 lety

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

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

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

  • @amansarma417
    @amansarma417 Před 4 lety +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

  • @prathameshmahankal4180

    Could someone please help me understand how the time complexity for the last solution is O(N^2)?

  • @rahulbhangale4656
    @rahulbhangale4656 Před 2 lety

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

  • @LovelyMountainGoat-rd7qy
    @LovelyMountainGoat-rd7qy Před 6 měsíci

    Thank you😇

  • @pallabghosh3840
    @pallabghosh3840 Před 2 lety

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

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

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

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

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

  • @rushabhlegion2560
    @rushabhlegion2560 Před rokem

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

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

    Good Explanation!

  • @sarathgovind.k.k7951
    @sarathgovind.k.k7951 Před 3 lety +2

    very good explanation

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

    THE BEST TUTORIAL

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

    Great sir, as usual😋

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

    Great explanation brother

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

    Excellent!

  • @shaileshhegde9205
    @shaileshhegde9205 Před 3 lety

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

  • @RahulKumar-qu1if
    @RahulKumar-qu1if Před 4 lety +1

    Thank you!🔥

  • @shivanggupta5421
    @shivanggupta5421 Před 4 lety

    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

  • @jatinshrivastava4231
    @jatinshrivastava4231 Před 2 lety

    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?

  • @chetanpatteparapu7600
    @chetanpatteparapu7600 Před 3 lety +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;
    }

  • @ritikgandhi3605
    @ritikgandhi3605 Před 4 lety +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  Před 4 lety +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.

  • @raj.saurabhh
    @raj.saurabhh Před 2 lety

    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

  • @blume0f
    @blume0f Před 4 lety +5

    awesome sir

  • @mahipalsingh-yo4jt
    @mahipalsingh-yo4jt Před 3 lety +1

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

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

    Nice Explanation

  • @sarvagyaiitmadras8727
    @sarvagyaiitmadras8727 Před 3 lety +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 ???

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

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

  • @jaredmomanyi8178
    @jaredmomanyi8178 Před rokem

    works like magic

  • @subratarudra2745
    @subratarudra2745 Před rokem

    Nice explanation sir

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

    Awesome bro!!

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

    very nice explanation

  • @jeevanr5814
    @jeevanr5814 Před 3 lety

    Dp approach is not working for some testcase can you please check it

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

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

  • @lifestoriesfromearth6271

    which tool are you using for whiteboard

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

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

  • @paragroy5359
    @paragroy5359 Před 3 lety +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

  • @kercat89
    @kercat89 Před 3 lety +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  Před 3 lety +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 Před 3 lety +1

      @@techdose4u That makes sense. Thank you!

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

    🔥solution

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

    awesome

  • @yashgoswami5374
    @yashgoswami5374 Před 4 lety

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

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

    Thank you

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

    TQ bro!😃

  • @abdelrhmansayed340
    @abdelrhmansayed340 Před rokem +1

    thanks

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

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

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

      Maybe try with Dijkstra graph algorithm.

    • @harshitchoukse2602
      @harshitchoukse2602 Před 2 lety

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

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

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

  • @amitavamozumder73
    @amitavamozumder73 Před 3 lety +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  Před 3 lety +1

      You can

    • @amitavamozumder73
      @amitavamozumder73 Před 3 lety

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

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

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

    • @techdose4u
      @techdose4u  Před 4 lety

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

  • @InsightWeaver
    @InsightWeaver Před 2 lety

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

  • @jameskurakula8560
    @jameskurakula8560 Před 3 lety

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

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

    Thanks

  • @kumaraakash25
    @kumaraakash25 Před 2 lety

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

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

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