Jump Game II - Greedy - Leetcode 45 - Python

Sdílet
Vložit
  • čas přidán 9. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    Coding Solutions: • Coding Interview Solut...
    Dynamic Programming Playlist: • House Robber - Leetco...
    Tree Playlist: • Invert Binary Tree - D...
    Linked List Playlist: • Reverse Linked List - ...
    Problem Link: neetcode.io/problems/jump-gam...
    0:00 - Read the problem
    2:06 - Drawing Explanation
    7:05 - Coding Explanation
    leetcode 45
    This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
    #sorted #array #python
  • Věda a technologie

Komentáře • 200

  • @NeetCode
    @NeetCode  Před 3 lety +25

    🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤

  • @dineshkumarkb1372
    @dineshkumarkb1372 Před 9 měsíci +30

    All your videos are a treasure . Every single one is worth rewatching during interviews. Never ever delete these videos or stop uploading new ones.

  • @allen724
    @allen724 Před 3 lety +95

    This is a great explanation. I like this method better than LeetCode's published solution! It is more intuitive for me. Thanks and keep up these videos.

    • @lakshmanprabhu6722
      @lakshmanprabhu6722 Před rokem +2

      Same here!. Went through a lot of solutions, but this is just gold.

  • @matthewtang1490
    @matthewtang1490 Před 3 lety +104

    Please don't stop making videos :) I just binged your DP playlist in 2 days

    • @NeetCode
      @NeetCode  Před 3 lety +32

      Wow, I bet you would nail any interview now! Thanks for the kind words

    • @crimsonghoul8983
      @crimsonghoul8983 Před 2 měsíci +1

      2 DAYS????

  • @aniketyadav6247
    @aniketyadav6247 Před 11 měsíci +10

    The below code also works :
    1.) Traverse the entire nums array. On each i-th iteration, update the farthest_jump to the max of current value of farthest_jump and i + nums[i]
    2.) If i is equal to the current jump we have completed the current jump and can now prepare to take the next jump (if required). So we increment the jump by 1 and set curr_jump to farthest jump.
    3.) If that's not the case then do not update the jumps variable and the curr_jump variable since we haven't yet completed the current jump.
    4.) In the end of the traversal you will get the minimum jumps.
    Hope this helps :)
    def jump(self, nums: List[int]) -> int:
    farthest_jump = 0
    jump = 0
    curr_jump = 0
    for i in range(len(nums)-1):
    # Find the Farthest Jump
    farthest_jump = max(farthest_jump, i + nums[i])
    # it means we have made the jump
    if i == curr_jump:
    # Point curr jump to the farthest jump
    curr_jump = farthest_jump
    jump += 1
    return jump

  • @acala127
    @acala127 Před 3 lety +15

    This is the most elegant and clear explanation I have seen for this problem. Thank you!

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

    please continue this series, you are born to teach coding to other people.

  • @protyaybanerjee5051
    @protyaybanerjee5051 Před 3 lety +16

    Man, we need more videos. Great production quality :)

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

    Your videos and explanations are some of the best on CZcams, really great stuff man, keep it up!

  • @ng.manisha
    @ng.manisha Před 6 měsíci +1

    You are literally a savior! I have my google interview lined up soon and all your videos actually teach me tricks how to think when faced with a problem!

  • @venkateshnaidu2133
    @venkateshnaidu2133 Před rokem +11

    Amazing solution, loved it! Here is a minor tweak to handle an edge case (no possible path)
    int minJumps(int arr[], int n){
    // Your code here
    int l=0, r=0;
    int jumps = 0;

    while(r < n-1) {
    int farthest = 0;
    for(int i = l; i r)
    return -1;

    jumps++;
    }

    return jumps;
    }

    • @akshatsamdani
      @akshatsamdani Před rokem

      Thanks for posting this. I was thinking about the same

    • @PorkBoy69
      @PorkBoy69 Před 2 měsíci

      The test cases are generated such that you can reach nums[n - 1].

    • @PRAVEENKUMAR-fi1wu
      @PRAVEENKUMAR-fi1wu Před 2 dny

      No need to do this. It is said in question. "We can always reach to the end" ​@@akshatsamdani

  • @licokr
    @licokr Před 9 měsíci +1

    Crazy. This channel explains coding solutions in the easiest way. It saves my life.

  • @divyanshkhetan
    @divyanshkhetan Před rokem

    This is a great approach. I especially liked how you related it to the concept of BFS. It helped in visualizing the approach so much!

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

    I am new to serious coding but great job! this took me some time and now way close to this neatness level!

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

    I don't think if I'll ever see a better explanation to this problem. Kudos man!

  • @arunraj2527
    @arunraj2527 Před 2 lety

    I love his patience and way of talking through the problem.

  • @rohanb9512
    @rohanb9512 Před rokem

    Nicely explained the intuition. Exactly wat i was looing for. Probably the best explanation in YT

  • @swathiayas
    @swathiayas Před 3 lety

    Really good videos! Been watching alot of your videos lately! Thank you making such awesome videos!

  • @kevintran6102
    @kevintran6102 Před rokem

    This explanation is crystal clear. Thank you!

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

    Really neat code! Nicely done and explained.

  • @Gnaneshh
    @Gnaneshh Před 2 lety +2

    One hell of an explanation ! Thank you

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

    Please please man, I love your channel so much, you have never disappointed me. Make a list of important greedy problems please

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

    The content of this channel is priceless. Been binge watching your videos

  • @697Alok
    @697Alok Před 3 lety +3

    What an explanation. Loved it :)

  • @Kushagra_21
    @Kushagra_21 Před 2 lety

    one of the best solution in internet for this question.
    Thanks a lot!!

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

    Excellent explanation. Much Thanks!

  • @meghaldarji598
    @meghaldarji598 Před 2 lety

    The best solution there is for this problem. I am saying after watching all other videos on this problem.🙌🙌

  • @yathartharana7956
    @yathartharana7956 Před rokem

    Searching the whole day and find this solution the best one 🙌🏼

  • @megavoltism
    @megavoltism Před 2 lety +5

    It's funny how he always colors-in his arrow heads
    Anyway, really cool insight about BFS!

  • @darkexodus6404
    @darkexodus6404 Před rokem +1

    Your explanation is too good! Understood it clearly.

  • @TheLaidia
    @TheLaidia Před 3 lety

    very clear explanation. Thank you!!

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

    Great explanation!!
    Even after this I was confused why the while condition is r < len(nums)-1, and not r < len(nums).
    I thought why can't we can change it to r < len(nums), and return res-1.
    This explains the algorithm better, since the result we are finding from the loop is the no. of blocks, and the no. of jumps is one less than no. of blocks.
    But this solution is not working for all the cases.

  • @ma_sundermeyer
    @ma_sundermeyer Před rokem +2

    Nice simplification of the BFS.. I had a similar idea but stayed with the conventional deque implementation:
    q = deque([(0,0)])
    max_i = 1
    while q:
    i,num_j = q.popleft()
    if i >= len(nums) - 1:
    return num_j
    for j in range(max_i, nums[i] + i + 1):
    q.append((j, num_j+1))
    max_i = max(max_i, nums[i] + i + 1)

  • @ankitchouhan8828
    @ankitchouhan8828 Před rokem

    Super clear explanation. Thanks!

  • @bahaaiman8588
    @bahaaiman8588 Před 2 lety +2

    This is the only one that I understood. Thanks a ton !

  • @aravinda1595
    @aravinda1595 Před rokem

    You are so good I just need to watch the explanation part and boom ! i can write my own code

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

    Awesome content as usual :)

  • @shashijais789
    @shashijais789 Před rokem

    Again Superb solution, which I was looking for! Thanks for this explanation.

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

    Thank you for the clear drawing explanation!

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

      Thanks, happy it was helpful 🙂

  • @heroicrhythms8302
    @heroicrhythms8302 Před rokem

    if we come to the middle of the array and can't reach the end anymore, that means we have encountered a 'zero'. then we should return -1. implement a check saying
    (if l>r: return -1)

  • @yashjain1011
    @yashjain1011 Před rokem

    such a nice explanation. This video was so great. You earned a subscriber.

  • @elements8630
    @elements8630 Před 2 lety

    great explanation! loved it

  • @krishnavamsichinnapareddy

    You simply nailed it. Love from India ♥️

  • @tori_bam
    @tori_bam Před 2 lety

    best explanation! Thank you so much!

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

    Great Explanation !!!

  • @anupamdubey5736
    @anupamdubey5736 Před 2 lety

    Best Explanation! Thanks

  • @MrExamer
    @MrExamer Před 2 lety

    great explanation on the BFS mind behind the problem

  • @VarunMittal-viralmutant
    @VarunMittal-viralmutant Před 2 lety +2

    The standard solution for this question is like the LIS variant which is O(N**2). And that gives TLE on LeetCode
    I think the solution described above works only when it is guaranteed that the end can be reached, else it fails. Correct ?
    Modified to take care of unreachable cases:
    def find_shortest_jump_path(jumps):
    l, r = 0, 0
    i = 0
    res = 0
    while l = len(jumps)-1 else -1

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

      Thank you very much! Your code solved my problem.
      But what's the variable ( i ) used for? why are we increasing it?

    • @VarunMittal-viralmutant
      @VarunMittal-viralmutant Před 5 měsíci +1

      @@God0fSloth That looks like some junk code, not used in final solution :)

  • @adwaitkesharwani3569
    @adwaitkesharwani3569 Před 2 lety

    Excellent explanation!!

  • @jaydhanwant4072
    @jaydhanwant4072 Před 2 lety

    What a great explaination!

  • @chandrachurmukherjeejucse5816

    Your explanation and drawing is just awesome.

  • @kewtomrao
    @kewtomrao Před 2 lety

    Awesome explanation!!
    I did the regualr BFS and got stuck in a MLE error.
    Now i know my mistakes.

  • @starkhunt2684
    @starkhunt2684 Před rokem

    Great explaination mate

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

    Oh man I unnecessarily used queue like in bfs. 🤧 I implemented exact bfs to find hops..
    But using the interval instead of queue was awesome 😎

  • @supervince110
    @supervince110 Před rokem

    You always have the simplest solution!

  • @Roastmaster704
    @Roastmaster704 Před rokem

    Keep Rocking !!

  • @shantanushende6
    @shantanushende6 Před 2 lety

    really really good! Felt like one comment did not do justice to the level of simplicity!

  • @asdfasyakitori8514
    @asdfasyakitori8514 Před 8 měsíci

    Great video!

  • @ge_song5
    @ge_song5 Před 4 měsíci

    question: why do we have to stop by the last_index - 1? while r < len(nums) - 1:

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

    You simplified it!! Thanks

  • @joshmccraney4020
    @joshmccraney4020 Před 2 lety

    amazing! subscribed

  • @subhajitrakshit9866
    @subhajitrakshit9866 Před 2 lety

    Love this solution...Thanks

  • @trantung2013
    @trantung2013 Před 2 lety

    Really elegant solution.

  • @avishekarora
    @avishekarora Před 2 lety

    Best Solution explaination, thanks

  • @alexandruoporanu8261
    @alexandruoporanu8261 Před 2 lety

    GREAT thanks a lot!

  • @sagarnair9021
    @sagarnair9021 Před rokem

    one line should be added after updating j
    i.e
    if j

  • @ankurtiwari5664
    @ankurtiwari5664 Před 2 lety

    i don't know python still i watch all ur videos
    Next level explanation of every approach

  • @apoorvgarg0204
    @apoorvgarg0204 Před 3 lety

    Fantastic!!

  • @loia5tqd001
    @loia5tqd001 Před dnem

    9:28 Why
    while r < len(nums) - 1
    not
    while r < len(nums)
    ?

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

    Thank god for you!

  • @stith_pragya
    @stith_pragya Před 8 měsíci +1

    Thank You So Much for this wonderful video................🙏🙏🙏🙏🙏🙏

  • @gokulnaathbaskar9808
    @gokulnaathbaskar9808 Před 2 lety

    Nice, looking at BFS for the first time in an array.

  • @DivyaSingh-bl4cj
    @DivyaSingh-bl4cj Před 2 lety

    Best explanation channels for python.

  • @dent1808
    @dent1808 Před rokem

    clearest explanation ever

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

    what a beautiful piece of code

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

    Your the GOAT!

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

    Amazing 🔥

  • @xinniu3145
    @xinniu3145 Před 2 lety

    Thank you for sharing. We can put farthest=0 before the while loop right?

  • @krateskim4169
    @krateskim4169 Před rokem

    Awesome explanation

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

    Just want to clarify that this is still a dynamic programming solution. That's because this solution is a moving window algorithm which are examples of dynamic programming. That is because they involve breaking the problem down into sub-problems and finding an optimal answer to those sub-problems, thus finding the optimal answer to the main problem. In this case the main problem is optimizing the fewest jumps to get to the end. The smaller sub-problem is finding the max jump within the current window.

  • @user-sw2wq5fw9n
    @user-sw2wq5fw9n Před rokem

    Best channel for explaining the leetcode problems to a dumbo like me

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

    whats the reason that it is "while r < len(nums) - 1:" not just "while r < len(nums) :"?

    • @arunavbhattacharya3353
      @arunavbhattacharya3353 Před 2 lety

      I fail to intuitively understand why do we need to iterate till n-1 instead of n

    • @eternalmeme7920
      @eternalmeme7920 Před 2 lety

      @@arunavbhattacharya3353 It's because, 1) All no. are positive, therefore if we touch the n-2 element, i.e. r=n-2, then we are iterating from l to r(inclusive), if we iterate at r=n-2, then since all no. positive, farthest will definitely be greater than >=n-1, therefore r

    • @visase2036
      @visase2036 Před rokem +1

      One of the main reasons for this is ,
      Since we are accounting the 1st jump at position 0 , we are not considering the last element to calculate the answer ie
      [2,3,1,1,4]
      We re incrementing ans+1 by taking 2 into account , which is not necessary if you work logically and since we are accounting that as one jump we are ignoring the last element!

    • @pruthvirajpatil7798
      @pruthvirajpatil7798 Před 9 měsíci

      Simple - Because if r is at len(nums)-1, we would have achieved the goal. No need to proceed ahead.

  • @aashishmalhotra
    @aashishmalhotra Před rokem

    Great explanation

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

    How is this solution a O(n)? Isnt there a for loop inside a while loop which makes it a O(n^2)?

  • @passionate_coder9249
    @passionate_coder9249 Před 2 lety

    Thank you so much

  • @ekanshsharma1309
    @ekanshsharma1309 Před rokem +2

    why we write r < nums.size() - 1.....
    not just r< nums.size()??

    • @user-yn6bj3ot2b
      @user-yn6bj3ot2b Před 13 dny

      Because if r is at nums.size, then it has to terminate because it has reached the final index.

  • @dennisg3683
    @dennisg3683 Před 4 měsíci

    Why does the first time iterating through the array the for loop starts at 0 and goes to just the first index (0 + 1)?

  • @algorithmo134
    @algorithmo134 Před 3 lety

    @NeetCode Can we use a heap to find the maximum steps we can jump instead of looping over all the number of steps we can take and then finding the maximum?

  • @appi147
    @appi147 Před rokem

    amazing explanation

  • @raj_kundalia
    @raj_kundalia Před rokem

    thank you!

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

    brilliant but I wouldnt be able to solve this by myself in a coding interview. Very clever indeed.

  • @NikhilKumar-mn8py
    @NikhilKumar-mn8py Před 2 lety

    Well explained

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

    I used a Dijkstra's approach to solve the problem, but this is a simpler and quicker answer... wow.

  • @sunshine-mc2oi
    @sunshine-mc2oi Před 2 lety

    Thank you for the awesome video. It's super easy to understand. Is there any chance you can make a video about 1326. Minimum Number of Taps to Open to Water a Garden and Video Stitching, they seem relevant to this topic. Thank you so much.

  • @katie_chan
    @katie_chan Před 3 lety

    Man I have to say "Bravo"!

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

    how would you come up with this in an interview, I could come up with the DP solution, but its n^2 complexity

  • @arihantjain3274
    @arihantjain3274 Před rokem

    Best explanation....

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

    Masterpiece.

  • @sirpsychosexy
    @sirpsychosexy Před rokem +1

    thank you code papi. i love you papi.

  • @shantanushende6
    @shantanushende6 Před 2 lety

    Legendary!!!!