Тёмный
No video :(

Jump Game II - Greedy - Leetcode 45 - Python 

NeetCode
Подписаться 806 тыс.
Просмотров 190 тыс.
50% 1

Опубликовано:

 

5 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 209   
@NeetCode
@NeetCode 3 года назад
🚀 neetcode.io/ - I created a FREE site to make interview prep a lot easier, hope it helps! ❤
@dineshkumarkb1372
@dineshkumarkb1372 11 месяцев назад
All your videos are a treasure . Every single one is worth rewatching during interviews. Never ever delete these videos or stop uploading new ones.
@naive-fleek7420
@naive-fleek7420 8 месяцев назад
during interviews??
@dineshkumarkb1372
@dineshkumarkb1372 8 месяцев назад
@@naive-fleek7420 I meant during prep for interviews. It’s implied dude.
@allen724
@allen724 3 года назад
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 Год назад
Same here!. Went through a lot of solutions, but this is just gold.
@matthewtang1490
@matthewtang1490 3 года назад
Please don't stop making videos :) I just binged your DP playlist in 2 days
@NeetCode
@NeetCode 3 года назад
Wow, I bet you would nail any interview now! Thanks for the kind words
@crimsonghoul8983
@crimsonghoul8983 4 месяца назад
2 DAYS????
@aniketyadav6247
@aniketyadav6247 Год назад
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
@venkateshnaidu2133
@venkateshnaidu2133 Год назад
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 Год назад
Thanks for posting this. I was thinking about the same
@PorkBoy69
@PorkBoy69 4 месяца назад
The test cases are generated such that you can reach nums[n - 1].
@PRAVEENKUMAR-fi1wu
@PRAVEENKUMAR-fi1wu 2 месяца назад
No need to do this. It is said in question. "We can always reach to the end" ​@@akshatsamdani
@acala127
@acala127 3 года назад
This is the most elegant and clear explanation I have seen for this problem. Thank you!
@prashantgupta6160
@prashantgupta6160 3 года назад
please continue this series, you are born to teach coding to other people.
@licokr
@licokr 11 месяцев назад
Crazy. This channel explains coding solutions in the easiest way. It saves my life.
@karthikinamanamelluri7208
@karthikinamanamelluri7208 9 месяцев назад
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.
@ng.manisha
@ng.manisha 8 месяцев назад
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!
@iamnoob7593
@iamnoob7593 17 дней назад
did u make it into Google?
@protyaybanerjee5051
@protyaybanerjee5051 3 года назад
Man, we need more videos. Great production quality :)
@heroicrhythms8302
@heroicrhythms8302 Год назад
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)
@VarunMittal-viralmutant
@VarunMittal-viralmutant 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 7 месяцев назад
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 7 месяцев назад
@@God0fSloth That looks like some junk code, not used in final solution :)
@ma_sundermeyer
@ma_sundermeyer Год назад
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)
@megavoltism
@megavoltism 2 года назад
It's funny how he always colors-in his arrow heads Anyway, really cool insight about BFS!
@ssvivek4
@ssvivek4 7 месяцев назад
I don't think if I'll ever see a better explanation to this problem. Kudos man!
@adityagoyal4299
@adityagoyal4299 5 месяцев назад
The content of this channel is priceless. Been binge watching your videos
@sniper324
@sniper324 3 года назад
Your videos and explanations are some of the best on RU-vid, really great stuff man, keep it up!
@denshaSai
@denshaSai 2 года назад
whats the reason that it is "while r < len(nums) - 1:" not just "while r < len(nums) :"?
@arunavbhattacharya3353
@arunavbhattacharya3353 2 года назад
I fail to intuitively understand why do we need to iterate till n-1 instead of n
@eternalmeme7920
@eternalmeme7920 2 года назад
@@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 2 года назад
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 11 месяцев назад
Simple - Because if r is at len(nums)-1, we would have achieved the goal. No need to proceed ahead.
@darkexodus6404
@darkexodus6404 Год назад
Your explanation is too good! Understood it clearly.
@divyanshkhetan
@divyanshkhetan Год назад
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!
@bahaaiman8588
@bahaaiman8588 3 года назад
This is the only one that I understood. Thanks a ton !
@NeetCode
@NeetCode 3 года назад
Happy to help!
@akshatgupta107
@akshatgupta107 3 года назад
Please please man, I love your channel so much, you have never disappointed me. Make a list of important greedy problems please
@ahmad3823
@ahmad3823 2 года назад
I am new to serious coding but great job! this took me some time and now way close to this neatness level!
@ekanshsharma1309
@ekanshsharma1309 Год назад
why we write r < nums.size() - 1..... not just r< nums.size()??
@user-yn6bj3ot2b
@user-yn6bj3ot2b 2 месяца назад
Because if r is at nums.size, then it has to terminate because it has reached the final index.
@pranavmaiya4386
@pranavmaiya4386 6 дней назад
hey did you get placed?
@arunraj2527
@arunraj2527 2 года назад
I love his patience and way of talking through the problem.
@yathartharana7956
@yathartharana7956 Год назад
Searching the whole day and find this solution the best one 🙌🏼
@ge_song5
@ge_song5 6 месяцев назад
question: why do we have to stop by the last_index - 1? while r < len(nums) - 1:
@stith_pragya
@stith_pragya 10 месяцев назад
Thank You So Much for this wonderful video................🙏🙏🙏🙏🙏🙏
@meghaldarji598
@meghaldarji598 2 года назад
The best solution there is for this problem. I am saying after watching all other videos on this problem.🙌🙌
@commandernorton88
@commandernorton88 2 года назад
Drinking game: take a sip when he says "Right?"
@user-sw2wq5fw9n
@user-sw2wq5fw9n Год назад
Best channel for explaining the leetcode problems to a dumbo like me
@sagarnair9021
@sagarnair9021 Год назад
one line should be added after updating j i.e if j
@kashishsharma6809
@kashishsharma6809 2 года назад
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 😎
@sirpsychosexy
@sirpsychosexy Год назад
thank you code papi. i love you papi.
@rohanb9512
@rohanb9512 2 года назад
Nicely explained the intuition. Exactly wat i was looing for. Probably the best explanation in YT
@loia5tqd001
@loia5tqd001 Месяц назад
9:28 Why while r < len(nums) - 1 not while r < len(nums) ?
@abibhavankumar2522
@abibhavankumar2522 23 дня назад
The array positions starts from 0 to length of array - 1. If you go till len(nums) then you will be considering an extra element that is not present in the array. Hope that clears your doubt!
@Gnaneshh
@Gnaneshh 2 года назад
One hell of an explanation ! Thank you
@chandrachurmukherjeejucse5816
@chandrachurmukherjeejucse5816 7 месяцев назад
Your explanation and drawing is just awesome.
@kevintran6102
@kevintran6102 2 года назад
This explanation is crystal clear. Thank you!
@aravinda1595
@aravinda1595 Год назад
You are so good I just need to watch the explanation part and boom ! i can write my own code
@user-pn9sr2rq3z
@user-pn9sr2rq3z 5 месяцев назад
great explanation and video! Espcially coloring. Unfortuntatelly does not work on leetcode any longer , giving timeout exceeded error.
@huatsaisoTM
@huatsaisoTM 3 года назад
Thank you for the clear drawing explanation!
@NeetCode
@NeetCode 3 года назад
Thanks, happy it was helpful 🙂
@themagickalmagickman
@themagickalmagickman Год назад
I used a Dijkstra's approach to solve the problem, but this is a simpler and quicker answer... wow.
@MrExamer
@MrExamer 2 года назад
great explanation on the BFS mind behind the problem
@ohmegatech666
@ohmegatech666 5 месяцев назад
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.
@shantanushende6
@shantanushende6 3 года назад
really really good! Felt like one comment did not do justice to the level of simplicity!
@ardhidattatreyavarma5337
@ardhidattatreyavarma5337 7 месяцев назад
what a beautiful piece of code
@krishnavamsichinnapareddy
@krishnavamsichinnapareddy 2 года назад
You simply nailed it. Love from India ♥️
@shashijais789
@shashijais789 2 года назад
Again Superb solution, which I was looking for! Thanks for this explanation.
@Kushagra_21
@Kushagra_21 2 года назад
one of the best solution in internet for this question. Thanks a lot!!
@ankurtiwari5664
@ankurtiwari5664 2 года назад
i don't know python still i watch all ur videos Next level explanation of every approach
@kewtomrao
@kewtomrao 2 года назад
Awesome explanation!! I did the regualr BFS and got stuck in a MLE error. Now i know my mistakes.
@venkatrampramod7978
@venkatrampramod7978 Год назад
Your solutions are absolutely brilliant. I love the way you break down the solution with diagrams.
@697Alok
@697Alok 3 года назад
What an explanation. Loved it :)
@gokulnaathbaskar9808
@gokulnaathbaskar9808 2 года назад
Nice, looking at BFS for the first time in an array.
@Cld136
@Cld136 3 года назад
Excellent explanation. Much Thanks!
@vishalmishra7018
@vishalmishra7018 3 года назад
Really neat code! Nicely done and explained.
@charan775
@charan775 Год назад
This has got to be the best intuitive explanation out there for this problem
@supervince110
@supervince110 2 года назад
You always have the simplest solution!
@vasumahalingam5162
@vasumahalingam5162 8 месяцев назад
brilliant but I wouldnt be able to solve this by myself in a coding interview. Very clever indeed.
@shantanukumar4081
@shantanukumar4081 2 года назад
Great Explanation !!!
@DivyaSingh-bl4cj
@DivyaSingh-bl4cj 2 года назад
Best explanation channels for python.
@user-2802cvsfkj
@user-2802cvsfkj Год назад
this is nuts dawg, who allowed this to exist. im literally shaking and crying rn, wtf.
@premthapa9959
@premthapa9959 Год назад
i cant fathom how easily u did smthing i took hours and stil couldnt crack
@allwell8570
@allwell8570 8 месяцев назад
You simplified it!! Thanks
@aishwaryaranghar3385
@aishwaryaranghar3385 3 года назад
i tried this code but it somehow throws tle. would be glad if you let me know a little updation in the code. thanks
@sauravsingh7157
@sauravsingh7157 2 года назад
It's giving TLE because this code goes in infinite loop in cases where we can't reach the end of the array. Ex- 1 2 0 0 6 7 - for this test case loop will never break. Here is a working code : def minJumps(self, arr, n): res = 0 l= r = 0 flag = 0 while r < len(arr) -1: farthest = 0 for i in range(l,r+1): farthest = max(farthest,i + arr[i]) l=r+1 r= farthest if l > r: flag =1 break res+=1 if flag ==1: return -1 return res
@jhanvisaraswat6976
@jhanvisaraswat6976 Год назад
wow, BFS. Never thought it could be done like that
@amrutaparab4939
@amrutaparab4939 5 месяцев назад
Thank god for you!
@yashjain1011
@yashjain1011 Год назад
such a nice explanation. This video was so great. You earned a subscriber.
@thevagabond85yt
@thevagabond85yt Год назад
I programmed by modifying Greedy Approach of Jump Game(I) : ``` class Solution { public int jump(int[] nums) { int N= nums.length, goal= N-1, jumpCount= 0; while(goal >0) { for(int i=0; i= goal) { goal= i; jumpCount++; break; } // if }//for }//while return jumpCount; } } ```
@tobito__
@tobito__ 3 года назад
How is this solution a O(n)? Isnt there a for loop inside a while loop which makes it a O(n^2)?
@abhinav-lq9ms
@abhinav-lq9ms Месяц назад
I think it's O(n) since we are always updating l to be r+1, so it won't again traverse the same value
@rabbyhossain6150
@rabbyhossain6150 10 месяцев назад
Memory Complexity: O(n) class Solution: def jump(self, nums: List[int]) -> int: steps = 0 visited, q = set(), collections.deque() q.append(0) visited.add(0) while q: length = len(q) for _ in range(length): idx = q.popleft() if idx == len(nums) - 1: return steps for pos in range(1, nums[idx] + 1): if (idx + pos) not in visited: q.append(idx + pos) visited.add(idx + pos) steps += 1
@venkatsaireddy1412
@venkatsaireddy1412 8 месяцев назад
why left is re-initialised with only right +1, it can be moved to more than right +1?
@swathiayas
@swathiayas 3 года назад
Really good videos! Been watching alot of your videos lately! Thank you making such awesome videos!
@amarrajeev2903
@amarrajeev2903 Год назад
I think the edge cases also must be handled in the code. Suppose if the Algorithm could not find the minJumps it should return -1 as such. Thoughts on this?
@markolainovic
@markolainovic Год назад
No need, in the description it says that the solution existence is guaranteed.
@Kellykmixtape
@Kellykmixtape 5 месяцев назад
bro is a genius
@dent1808
@dent1808 Год назад
clearest explanation ever
@TheLaidia
@TheLaidia 3 года назад
very clear explanation. Thank you!!
@avishekarora
@avishekarora 2 года назад
Best Solution explaination, thanks
@amanshaukat1105
@amanshaukat1105 2 года назад
This is a great explanation. Very intuative. lets say it is not guaranteed that answer will exist, and we have to return -1 in such case. How could we handle this. Please help.
@trantung2013
@trantung2013 3 года назад
Really elegant solution.
@dennisg3683
@dennisg3683 6 месяцев назад
Why does the first time iterating through the array the for loop starts at 0 and goes to just the first index (0 + 1)?
@sunshine-mc2oi
@sunshine-mc2oi 2 года назад
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.
@xinniu3145
@xinniu3145 2 года назад
Thank you for sharing. We can put farthest=0 before the while loop right?
@anupamdubey5736
@anupamdubey5736 2 года назад
Best Explanation! Thanks
@bibibaba2505
@bibibaba2505 Год назад
best answer I have ever seen.
@SMAsaduzzamanAsad880
@SMAsaduzzamanAsad880 3 года назад
Very good explanation!
@tori_bam
@tori_bam 2 года назад
best explanation! Thank you so much!
@gulershad4375
@gulershad4375 2 года назад
def jump(nums): jump = 0 farthest = float('-inf') end = 0 for i in range(len(nums)): farthest = max(farthest, nums[i]) + 1 if i == end and i != len(nums) - 1: jump += 1 end = farthest return jump
@krateskim4169
@krateskim4169 Год назад
Awesome explanation
@darshansimha2166
@darshansimha2166 2 года назад
Nice video, I understand the solution. But I am having a tough time understanding the complexity for an array of all 1's wont the for loop inside run for every iteration in the array, so won't that make it O(n^2)?
@divyasri9432
@divyasri9432 2 года назад
I have got the same doubt forloop inside while loop will give time complexity O(n^2) how does this become optimal solution?
@bmusuko
@bmusuko 2 года назад
​@@divyasri9432 I think the key here, we shift the left pointer to r+1 so we only inspect each element in the array once, it means it is o(n)
@minhthinhhuynhle9103
@minhthinhhuynhle9103 Год назад
2 loops doesn't mean O(N^2)
@ronniey4231
@ronniey4231 10 месяцев назад
please please update more videos!!!❤❤❤
@asdfasyakitori8514
@asdfasyakitori8514 10 месяцев назад
Great video!
@subhajitrakshit9866
@subhajitrakshit9866 2 года назад
Love this solution...Thanks
@LeCharles-bw4wp
@LeCharles-bw4wp 9 месяцев назад
Thanks.But I suppose the time should be O(n squares)
@francescosacripante1661
@francescosacripante1661 Год назад
Correct me if I'm wrong, but couldn't we solve it by using Dijkstra algorithm? I mean we could create a graph and with this search for the shortest path to the end
@starkhunt2684
@starkhunt2684 2 года назад
Great explaination mate
@symbol767
@symbol767 2 года назад
Greedy algorithms are so weird, there are so many different implementations of it. There is no 1 standard structure so far from what I seen
Далее
Jump Game - Greedy - Leetcode 55
16:28
Просмотров 234 тыс.
The LeetCode Fallacy
6:08
Просмотров 492 тыс.
НЕДОВОЛЬНА УСЛУГОЙ #shorts
00:27
Просмотров 19 тыс.
Cute kitty gadget 💛💕
00:23
Просмотров 4,7 млн
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Просмотров 200 тыс.
How I would learn Leetcode if I could start over
18:03
Просмотров 484 тыс.
8 patterns to solve 80% Leetcode problems
7:30
Просмотров 344 тыс.
LeetCode was HARD until I Learned these 15 Patterns
13:00
Unique Paths - Dynamic Programming - Leetcode 62
10:48
Просмотров 126 тыс.
Jump game | Leetcode #55 | Valley peak approach
12:28
Просмотров 188 тыс.
5 Useful F-String Tricks In Python
10:02
Просмотров 301 тыс.
НЕДОВОЛЬНА УСЛУГОЙ #shorts
00:27
Просмотров 19 тыс.