Jump Game - Greedy - Leetcode 55

Поделиться
HTML-код
  • Опубликовано: 29 ноя 2024

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

  • @davidbanda4727
    @davidbanda4727 3 года назад +204

    Excellent explanation, you explain the algorithms so easy and well. Observation: You can write the last line of code as: return goal == 0. regards!

    • @pankajjatav6448
      @pankajjatav6448 Год назад +2

      Also you can start loop from second last element: for i in range(len(nums)-2, -1, -1):

    • @yonavoss-andreae4952
      @yonavoss-andreae4952 Год назад

      @@pankajjatav6448 that triggers an edge case in which two elements returns false ie [1,2]

    • @gordonwu8117
      @gordonwu8117 11 месяцев назад

      @@yonavoss-andreae4952 if length is 0 then "i" will start on index 0, which works as intended

    • @brain_station_videos
      @brain_station_videos 8 месяцев назад

      or simply return not goal

  • @gunishjain9307
    @gunishjain9307 2 года назад +51

    12:00 jaw dropping intuition, I could have never thought about it. Thanks for the explanation.

  • @hash00ify
    @hash00ify 2 года назад +49

    we can start the loop from the len(nums) - 2 position since goal is already set at the last position when we declare it.

    • @shashanksrivastava7262
      @shashanksrivastava7262 Год назад +2

      I am acturally surprised how his code actually worked like, wouldn't i+nums[i] be always greater than goal ?

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

      @@shashanksrivastava7262 Yes I'm also thinking about that too.

    • @quanghuyluong1249
      @quanghuyluong1249 Год назад +4

      @@shashanksrivastava7262 Consider [3,2,1,0,4]: i+nums[i] would not be greater and the goal will never be shifted

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

      @@shashanksrivastava7262 Yes, i+nums[i] would be greater than goal for the first iteration, which would satisfy the if statement but the goal will be the same, i.e the last index and the program would move on the next iteration and work as usual.

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

      Thats why in this example we cannot reach last element. Algorithm works

  • @andrepinto7895
    @andrepinto7895 2 года назад +40

    There is no need to start from the end and move backwards. You can naturally progress from the beginning, like this:
    int reach = 0;
    for (int i = 0; i < nums.length && i = nums.length-1;

    • @ma_sundermeyer
      @ma_sundermeyer 2 года назад +5

      yeah, also started from the beginning, it's more intuitive. You can also stop early at zeros that you can't cross:
      max_index = -1
      for i in range(len(nums)-1):
      if nums[i] == 0 and max_index

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

      @@ma_sundermeyer Why does everyone start from the end? Does it help with other problems that use a similar solution (that can't be implemented front-forwards)? From the beginning is a million times easier to remember.

    • @aesophor
      @aesophor Год назад +3

      @@PippyPappyPatterson I disagree. NeetCode's solution is easier to understand imo.

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

      @@aesophor do u normally iterate across ur arrays in reverse? or forwards?

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

      @@PippyPappyPatterson iterating over an array in reverse is not a rarely used dp technique.

  • @aryehakierman6388
    @aryehakierman6388 Год назад +2

    thats an awesome solution and explination!!
    I thought of an answer where we only stop our iteration once we come upon a zero. then we just check if we can if the zero can be jumped over by previous elements. the only problem is the edge case where nums= [0],where you got check for it.
    var jump = function (nums) {
    if (nums.length === 1) return true;
    let prevPosition, prevValue;
    let passFlag = true;
    for (let i = 0; i < nums.length - 1; i++) {
    if (nums[i] === 0) {
    passFlag = false;
    prevPosition = i - 1;
    while (prevPosition >= 0) {
    prevValue = nums[prevPosition];
    if (prevPosition + prevValue > i) {
    passFlag = true;
    break;
    }
    prevPosition--;
    }
    if (!passFlag) return false;
    }
    }
    return true;
    };

  • @pritampawar6478
    @pritampawar6478 2 года назад +43

    that explanation for greedy part was just awesome🔥🔥

  • @anjanobalesh8046
    @anjanobalesh8046 2 года назад +11

    The if condition can be modified to
    If nums [i] >= goal - i
    i.e if the value at the current index is greater than or equal to the difference between the goal and the index
    For better understanding 😄 thank you

  • @kalintoshev
    @kalintoshev 2 года назад +52

    The tricky part of the greedy is to prove that it actually works; we clearly have multiple options for moving the goal and we always pick the first one. How do we guarantee that we are not going to get stuck using this approach?

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

      how it becomes greedy solution please explain it.

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

      This is what I have a little trouble wrapping my brain around. We always pick the first option, but what if the first option is 0? Then we're stuck lol. I guess you could add extra logic to handle that but the greedy solution doesn't seem to have include that

    • @VipulDessaiBadGAMERbaD
      @VipulDessaiBadGAMERbaD 2 года назад +7

      but this prob is not to find optimal path but to find only if we can reach the destination, that is why its okay to select the first elment.

    • @Sim0000n
      @Sim0000n 2 года назад +14

      @@mangalegends Let's consider the array 3105. Goal is 3, i is 3. I becomes 2, goal stays the same (as it is 0.) I becomes 1, Goal stays the same as 1+1 is not greater or equal than 3. i becomes 0, but as 0+3 ≥ 3, we're good. So no reason to be stucked

    • @jorgemejia1586
      @jorgemejia1586 Год назад +3

      Even if you hit a 0 during the loop, that’s fine. The goal post will be left at an actual reachable/moveable location (aka an index where the value is not zero)

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

    greedy approach is brilliant. love it

  • @yuzhenwang8103
    @yuzhenwang8103 11 месяцев назад +1

    Great Explanation! Thx for making it clearer for greedy algorithm

  • @ronitsrivastava377
    @ronitsrivastava377 3 месяца назад +1

    This solution is just wild. Easy and efficient. Love it

  • @baetz2
    @baetz2 Год назад +10

    You can also solve this problem by finding zeroes in the array and check if there are numbers before zeroes long enough to jump over zero. For example, if you see [3,2,1,0,...], you can instantly tell you're stuck at 0.

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

      that makes sense but this is still technically O(n^2) right?. consider this example [2,3,4,5,6,7,8,8,0,0,0,0,0,0,0,0,0,0,9]. For every non zero element, we have to do ~n/2 work to check if it crosses over all the zeros (i.e constant amount of work for every non zero element)

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

      Working backwards, if we record the index of the first encountered 0, then the work required to check if an element crosses is constant. @@tunepa4418

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

      @@tunepa4418 no, I think it would be the same way, except we just only start checking once we find a zero. I don't think it'd be any faster though... because you'd still have to check if each value is a zero...

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

      ​@@tunepa4418if we are going from the end of list and found a zero, and then found a long enough jump to jump over it, we dont care about zeroes between first zero and jump position

    • @856dtrad9
      @856dtrad9 Год назад

      @@tunepa4418 O(n)
      class Solution:
      def canJump(self, nums: List[int]) -> bool:
      obstacle = -1
      for pos in range(len(nums) - 2, -1, -1):
      if nums[pos] == 0 and obstacle == -1:
      obstacle = pos
      if pos + nums[pos] > obstacle:
      obstacle = -1

      return obstacle == -1

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

    You and Tech Dose are my go to for leetcodes.

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

      Yeah, Tech Dose is really good at explaining.

    • @MrYp-ds7sz
      @MrYp-ds7sz 3 года назад +4

      I found neetcode more clear and easy.

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

      @@MrYp-ds7sz neetcode>techdose

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

      @@nemesis_rc neetcode==techdose

  • @suhailf5014
    @suhailf5014 3 года назад +16

    These are the questions/solutions that make me fall in love with algorithms :)
    many many thanks @NeetCode

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

    That greedy solution is ingenius. I am in awe!!
    Thank you.

  • @guneskedi
    @guneskedi 7 месяцев назад

    Oh my god I cannot believe I can finally understand, design the steps and write the correct code! Finally my work paid off!!

  • @phlix1
    @phlix1 9 месяцев назад +2

    I love how simple the solution is. I was sketching out a very complex one :D

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

    Alternative:
    1) Start on the right
    2) Go to the left, skip all non-zeros
    3) On each zero, find any position on the left that can skip it - i.e. larger than the distance from it
    4) If there's none, return false
    5) If there's any, continue from there, to the point 2)
    6) Return true when reaching the left end.

  • @gompro
    @gompro 3 года назад +5

    This channel is so much underrated. This video is just amazing!

  • @SM-si2ky
    @SM-si2ky 2 года назад +7

    I could come up with the DP memorization solution by myself, but got TLE, the greedy solution is optimal but unintuitive.

    • @freindimania11
      @freindimania11 9 месяцев назад

      Had the same experience, DP with memo got me TLE, however DP with tabulation got through - although still slower than other submissions.

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

    For anyone who is interested in the dp solution ( C++ version).
    bool dfsJump(vector& nums, int i, vector& cache) {
    if (i >= nums.size() - 1) { // reaches or beyond last element
    return true;
    }
    if (cache[i] != -1) {
    return cache[i];
    }
    // starts from i, maximum can jump
    for (int j = 1; j

  • @yhbarve
    @yhbarve Месяц назад

    The greedy solution is simply lovely! So clever!

  • @sscapture
    @sscapture 4 месяца назад

    Spent couple of hours with this task :( after watching first 3 minutes of the video, was able to write the solution. You're God!

  • @meh4466
    @meh4466 5 месяцев назад +1

    My solution is exactly similar to this but a bit more readable :
    min_req = 1
    counter = len(nums)-2
    while(counter >= 0):
    if(nums[counter] >= min_req):
    counter -= 1
    min_req = 1
    else:
    counter -= 1
    min_req += 1
    if min_req == 1:
    return True
    return False

    • @kjplayz3064
      @kjplayz3064 5 месяцев назад

      you can write return (min_req == 1)

  • @siddhantwaghanna4795
    @siddhantwaghanna4795 Год назад +2

    For those who have the question of why is always first element chosen as the next goal in greedy approach:
    There are mainly two types of questions you might be facing:
    1. Why always chose the first element as next goal post
    2. What if I don't get a further route afterwards by choosing the first element. What if I would have chosen other element that time and I would have gotten answer ( In this case you must have thought what if I couldn't have reached 1 in any way, I would have missed the potential answer of keeping 3 as the next goal.....)
    Answer:
    According to the solution, we chose 1 as our goalpost. In the back of our mind we know it can also be reached by 3. you think that I might get stuck on further exploring the path with 1.
    ** Take a closer look, my friend, if you can reach 4 from 3, you will also definitely reach 1 from 3 ( because 4 is farther away from 1). So while choosing the first element you have the surety that if there is any other potential answer beyond that index, that index could also be reached with that potential answer(in this case 1 could also be reached by 3 as 4 was reachable by 3). And thus you know that you will get the answer by choosing the first element. **
    Hope this clears your doubt....

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

      Finally someone answered! Appreciated.

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

    Love when I can implement someone's explanation without directly looking at the implementation.
    Thank you so much brotha

  • @ku-1119
    @ku-1119 2 года назад +8

    Really good video, I was stuck trying to do it in a DP way, but this is really clean!
    Also, the last line can be simplified to "return goal == 0" as this returns a boolean.

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

      this is the dp solution in O(n^2), but only passes 77/170 on LC due to TLE. I think they really want you to use the greedy approach
      class Solution(object):
      def canJump(self, nums):
      dp = [0 for _ in range(len(nums))]
      # goal can be reached from itself
      dp[-1] = 1

      for i in range(len(nums)-2, -1, -1):
      for j in range(1, nums[i]+1):
      # as long as one of your descendants (who u can reach from your current spot) can reach the goal, you can too
      if (dp[i+j] == 1):
      dp[i] = 1
      # for better efficiency
      break;
      return dp[0]

  • @Kaviarasu_NS
    @Kaviarasu_NS 9 месяцев назад

    I have started to binge watch Neet ode recently, 2024 is going to be awesome ❤

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

    I had a different solution that worked as well. We only can't jump to the end if the array have an element 0 in it and this element isn't the last one. So I loop through every element and check if it was 0, if so, I loop backwards to check if there is an element that can jump over the zero, if so, I'll continue the loop, if not, I'll break and return false

    • @RS-vu4nn
      @RS-vu4nn 2 года назад +1

      He is doing exactly the same thing but more efficiently

  • @harshavardhini2082
    @harshavardhini2082 5 месяцев назад

    bro is a genius for coming up with that greedy solution THANK YOUU FOR THIS VIDEO!

  • @Andhere-Ki-Aahat
    @Andhere-Ki-Aahat 2 года назад +3

    Man excellent job. I went through many videos but wasn't able to understand. U made us all feel that it is very simple. Thanks a-lot again.

  • @yankindeez
    @yankindeez 2 года назад +13

    Thanks!

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

    Nice. I practiced the dp solution and got stuck on greedy. I was able to make the connection to the last and second before last elements , but couldn’t think of moving the goalpost as you say. Nice solution.

  • @marq_8976
    @marq_8976 8 месяцев назад +2

    I still don't understand how it works for the FALSE example.

  • @learnwithcode4211
    @learnwithcode4211 2 месяца назад

    People often feel frustrated when optimization is prioritized over brute-force solutions. It’s important to start with a simple brute-force approach to fully understand the problem before jumping into optimizations. This foundational step helps clarify the problem and makes it easier to build upon with efficient solutions.
    Let's focus on presenting clear brute-force solutions first and use general coding constructs to make problem-solving more accessible and translatable.

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

    This is the best greedy solution I have seen till now!

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

    Starting at the end, we always have to traverse the entire length of the array. Starting at the beginning is more performant as we can return true as soon as the current value is > last index - n.

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

    You can skip the last index check by initiating for loop len(nums) -2

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

    The greedy approach is simply mind-blowing!

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

    Optimization: Notice that you can always jump forward unless you run into a zero. Therefore, just check each zero (if any), and make sure there's a number to the left that's big enough to jump over it. It's a little more code, but much faster, especially if the array is huge but only has a few zeros. Here's my solution:
    start = 0
    while True:
    try:
    pos = nums.index(0, start, len(nums) - 1)
    except ValueError: # no more zeros found
    break
    for ptr in range(pos - 1, -1, -1):
    if nums[ptr] > pos - ptr:
    break
    else:
    return False
    start = pos + 1
    return True

  • @adilsaju
    @adilsaju 5 месяцев назад +2

    thats a unique greedy soln.! awesome!

  • @АлександрЯрулин-й7и
    @АлександрЯрулин-й7и 2 года назад +1

    Thanks. You're very talented in explanation.

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

    Java code the same
    public boolean canJump1(int[] nums) {
    int goal = nums.length - 1;
    for(int i = nums.length - 1; i>= 0; i--) {
    if(i + nums[i] >= goal) {
    goal = i;
    }
    }
    return goal == 0;
    }

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

    Amazing. You made this incredible video explaining the problem and you end it with "return True if goal == 0 else False" instead of just "return goal == 0".

    • @Rajmanov
      @Rajmanov 9 месяцев назад +1

      Due to its more comprehensive nature, simplicity doesn't always equate to superiority.

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

    amazing explanation. It really showcase why greedy approach can work wonders sometimes

  • @dinkleberg794
    @dinkleberg794 3 года назад +18

    Hey Neetcode, do you have any videos on your routine when your were leetgrinding? Like how many questions per day u were doing and how long it took u to complete the 75 questions list?

    • @kneeyaa
      @kneeyaa 2 года назад +6

      I targeted 5 q each day to achieve all in 15 days

    • @haroldobasi2545
      @haroldobasi2545 2 года назад +24

      @@kneeyaa that’s crazy actually

  • @findingMyself.25yearsago
    @findingMyself.25yearsago 2 года назад

    Forward approach
    def canJump(self, nums: List[int]) -> bool:
    n = len(nums)
    max_goal_reached = 0
    for index in range(n):
    if index > max_goal_reached:
    return False
    new_goal = nums[index] + index
    if new_goal > max_goal_reached:
    max_goal_reached = new_goal
    if max_goal_reached >= n - 1:
    return True
    return False
    Just adding my DP solution for understanding the approach, but anyhow as he said in video because of n^2 it will give TLE
    def canJump(self, nums: List[int]) -> bool:
    n = len(nums)
    dp = set()
    def dfs(index):
    if index in dp:
    return False
    if index >= n - 1:
    return True
    for next_index in reversed(range(index + 1, nums[index] + index + 1)):
    if next_index in range(n):
    result = dfs(next_index)
    dp.add(next_index)
    if result:
    return True
    return False
    return dfs(0)

  • @BillyL6
    @BillyL6 Месяц назад

    I got confused why you counted the goal post itself `for i in range(len(nums) - 1, -1, -1):`, but in your python solution on neetcode, you did `for i in range(len(nums) - 2, -1, -1):`, which makes more sense in my head. Both solutions work since even -1 doesn't move the goal post at all, but in my visual mind it wanted to start at -2. Thanks!

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

    for the greedy explanation, what gives us the right to shift the goal post to the FIRST item that can reach it? There can be multiple items that can reach the goal post that are more "left"? ie in [1,3,2,1,5] we shift the goal from 5 to 1 immediately upon encountering 1, instead of looking further to the left such as 2....why is this greediness guaranteed to produce the correct result?

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

    Outstanding illustration with the diagrams. I just tried out the same code looping i from len(nums) - 2 to -1 because anyway the first run didn't alter the goal's position and it got accepted :) thank you so much!

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

    I think u can also solve it in O(nlogn) using a BIT or segment tree , where u will start from the end and see whether the current node range (l = i , r = i+nums[i]) summation is greater than 0 or r >= nums.size() , if so then update the current node to be one and continue

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

    another solution that come to my mind is building adj list (graph) from the array and then use BFS from index 0 to find path to last index, this should have time complexity O(N) and space complexity O(E) which E is edges in graph, but greedy solution is also awesome since space complexity is O(1) 👍

    • @findingMyself.25yearsago
      @findingMyself.25yearsago 2 года назад

      yes it would be another great approach, can you share the code if you have in handy? would be helpful

    • @TheChlomek
      @TheChlomek 9 месяцев назад

      @@findingMyself.25yearsago
      I wrote this code for this in case it helps anyone in future. It passes 75 of the test cases flagging a 'Memory Limit Exceeded' issue
      class Solution:
      def canJump(self, nums: List[int]) -> bool:
      adj = defaultdict(list)
      for i in range(len(nums)):
      for j in range(nums[i]+1):
      adj[i].append(i+j)
      q = deque()
      q.append(0)
      visited = set()
      while q:
      currIndex = q.popleft()
      if currIndex == len(nums) - 1: return True # we've hit the end
      if currIndex in visited: continue
      visited.add(currIndex)
      for nextIndex in adj[currIndex]:
      q.append(nextIndex)
      return False

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

    The simpler approach would be:
    For each reachable index:
    we update the max reachable index which we can reach.
    If anytime we reach till end we found the solution.
    working code:
    int index = 0, reachable = 0, n = nums.length;
    while (index = n - 1) {
    return true;
    }
    index++;
    }
    return false;

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

    Thank you for these videos, I found you recently and you are the channel I have been looking for

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

    Thank you so much sir! Your logics and way of explaining is really impressive and make attention to the solution.

  • @Dhruvbala
    @Dhruvbala 4 месяца назад

    If you want to figure out whether a goal is attainable, work backward to figure out what's the easiest first step. You can achieve your goal iff that first step is within reach.

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

    Thanks buddy. You're literally the best

  • @emilyplanes7082
    @emilyplanes7082 3 года назад +15

    Please keep posting.
    Also I have a recommendation. Please add python in your title and thumbnail. You will surely reach more people.
    Ex. Jump game leetcode python solution #55 - Greedy approach explained
    Thank you for making these videos.💯❤️

  • @alivation3409
    @alivation3409 Месяц назад

    Interesting! I went from start to end, basically making a greedy algo that way. I kind of like this solution better. I'm gonna convert it into ruby for anyone that finds this later in that language.

    • @alivation3409
      @alivation3409 Месяц назад

      def can_jump(nums)
      goal = nums.length - 1
      (nums.length - 1).downto(0) do |i|
      if i + nums[i] >= goal
      goal = i
      end
      end
      return goal == 0
      end

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

    your explanations are really easy to understand. I always look for your videos. I was looking for buy and sell stocks III and IV videos from your channel but did'nt find them. Watched other channel videos but they were not as easy to understand.

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

    O(n^2) DP solution gives TLE, thats pretty sad considering the greedy approach may not be apparent to many in an actual interview.

  • @janaSdj
    @janaSdj 3 месяца назад

    I solved it by using BFS technique:
    bool canJump(vector& nums) {
    int n = nums.size();
    queueq;
    q.push(0);
    vectorvisited(nums.size(),0);
    visited[0]=1;
    while(!q.empty()){
    int curInd = q.front();
    q.pop();
    if(nums[curInd]+curInd>=n-1){
    return true;
    }
    for(int i=1;i

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

    Great videos, can you also explain how you get the time complexities? I am not how sure how you got the n^n and n^2

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

      n^n happens because as for each index number explored, he recursively explores the indices reachable by it, however because he isn't caching it essentially we end up with a lot of repeated work like he mentions. A more visual way of thinking about it: [3,2,1,0,4]. I start with the 3 at index 0, and recursively call (which is the same as a Depth First Search stack implementation) each of the indices reachable (0+1,0+2,0+3) = (1,2,3), I start with index 1. It has a value of 2, same as before, I then have another recursive call to index 2 with value 1, until we reach 0. Now when the stack unfolds, BECAUSE we did not cache, we still end up calling all the branches as before. Meaning when we roll back to index 1 (the one that had value 2), we only explored the first of (1+1,1+2) aka index 2, but we didn't make a call yet for index 3. With Caching this is reduced significantly, and essentially becomes a n + (n-1) + (n-2) +...+1 complexity problem which, when we drop lower terms, we get as O(n^2). Hope this is more clear.

  • @MsSkip60
    @MsSkip60 3 года назад +9

    Get in there, Neetcode!!!! I'm not sure how you feel about it but man, your videos are top notch compared to rest of the leetcode content creators

  • @user-ul2mw6fu2e
    @user-ul2mw6fu2e 8 месяцев назад

    class Solution:
    def canJump(self, nums: List[int]) -> bool:
    l = len(nums) - 2
    r = len(nums) - 1
    curr_dist = 0
    while l > -1:
    if nums[l]>= r - l :
    r-=(r-l)
    elif nums[l] < r - l and l==0:
    return False
    l-=1
    return True

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

    Thanks mate, helped me a lot. Easy and very quick

  • @awsaf49
    @awsaf49 2 года назад +5

    I'm just wondering what would happen if it was mentioned that we have to choose the shortest path instead of any path? Then I think the Greedy technique might not have been worked...

  • @Comp-Code
    @Comp-Code 2 месяца назад

    your last line for the greedy solution can be simplified to return goal == 0 since "goal == 0" itself is a condition

  • @pritam-kunduu
    @pritam-kunduu Год назад

    The last statement can be simplified to just
    goal == 0
    Or even further
    bool(goal)

  • @eliabekun
    @eliabekun 8 месяцев назад

    Fantastic! I can't believe that is so simple...Amazing!

  • @Osman-ko8jy
    @Osman-ko8jy 2 года назад +2

    Not sure why the Memoization solution doesn't work with Python, but does for JAVA

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

    excellent video. I am learning a lot from your videos. Great work

  • @sampannapokhrel
    @sampannapokhrel 10 месяцев назад

    At 9:53, you said the time complexity is O(n ^2).If you use a Memoization Hash or array, it would be O(n).

  • @JimmyKal
    @JimmyKal 9 месяцев назад +1

    1 minute of silence for those that tried the brute force in an interview

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

    I went the opposite direction. I started at the beginning and had a pointer that stored the max jumpable value. If the max got stuck and the iterator went above the pointer, it would return false. If the right pointer went to the max index or above, it returns true. Just wanted to explain a different O(N) solution

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

      I did the same. For me that is intuitive. I don't know why the clever solutions always go backwards 😄. I saw the same thing with the Unique Paths problem as well.

  • @draugno7
    @draugno7 Месяц назад

    I don't know if we are expected to start the loop from the first index, I know that in that task about reaching the bottom right of the matrix, we could start at the end if we get the right solution. I will transform this to loop from 0, just in case

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

    Great explanation. No need of ternary tho, returning goal == 0 is enough.

  • @Gameplay-ps9ub
    @Gameplay-ps9ub Год назад

    One small nitpick in the implementation would be, that you could just return goal==0 (which evaluates to boolean value). Some could say using the ternary / if...else is more readable, but it's a matter of opinion I guess. Nevertheless, great video as always. I truly appreciate the way you explain algo, it's very clear imo. :)

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

    It's not clear why the greedy algorithm is guaranteed to find a solution, if one exists.
    Is it possible that for some input, with a solution, the greedy algorithm will not find a solution?

  • @Aminbenabdelhafidh
    @Aminbenabdelhafidh 2 месяца назад

    Great Solution and explanation, but instead of
    return True if goal == 0 else False
    you can just put
    return goal == 0

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

    Great explanation!! but wont the for loop start from len(nums)-2 ???

  • @jugsma6676
    @jugsma6676 7 месяцев назад

    This is the O(n^2) solution, but time exceeds in leetcode :
    def canJump(nums: list[int]) -> bool:
    cache = [False] * len(nums)
    cache[len(nums)-1] = True
    for i in range(len(nums)-1, -1, -1):
    for j in range(i+1 + nums[i]):
    cache[i] = cache[i] or cache[j]
    return cache[0]

  • @chanderthakur9005
    @chanderthakur9005 7 месяцев назад

    i am having a hard time understanding why the condition i + num[i] >= goal works?? can someone please explain , thanks.

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

    You made problem soo easy Sir!!!

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

    Is it just me or the DP solution giving TLE?

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

      Yes it gives me TLE too, idk why leetcode does that. For some reason they only accept the greedy solution.

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

      @@NeetCode Thank you.

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

      @@NeetCode can you give dp solution here pls

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

    Fantastic approach love you needcode

  • @ahmadbasyouni9173
    @ahmadbasyouni9173 4 месяца назад

    i never comment but this explanation made my jaw drop

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

    Your explanation works like magic! Thank you so much 😊

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

    awesome solution and explanation, thank you !

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

    May be we should take the range of i from last but one element to compare with goal not upto last element.

  • @SantoshKumar2
    @SantoshKumar2 6 месяцев назад

    God bless you! 😀
    This helped a lot.

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

    U a God
    class Solution(object):
    def canJump(self, nums):
    """
    :type nums: List[int]
    :rtype: bool
    """
    post = len(nums) - 1
    for i in range(len(nums)-1,-1,-1):
    if nums[i] + i >= post:
    post = i

    return True if post == 0 else False

  • @kjplayz3064
    @kjplayz3064 5 месяцев назад

    hi if it you could only jump a fixed length (e.g. if the number was 2, and you could only jump 2 spaces, not 1), could you still start from the end? Or must yoi use DP?

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

    Never stop making these please lol

  • @Ren-Ren-Ren-Ren
    @Ren-Ren-Ren-Ren 2 года назад

    I love you Mr. NeetCode.

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

    It fails for[2,0,0] as we are only checking jump by 1 from previous element of goalpost element.

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

    how will the greedy solution work if the input array is [2,3,1,0,4] ? return value should be true as you can jump from 3->4 but you can't shift from 0->4. where will you shift your goal on first iteration?

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

      you dont need to shift goal on first iterarion if its cant jump to lastest goal (in this case index 4), loop iterator move to 1 and then 3 and now (jump[i] + i >= goalPointer) which is 3 + 1 >= 4, mean we can shift goal pointer to index 1 (value 3) and so on.
      if the goal pointer reach index 0 then we return true, else return false.

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

    The for loop should start like this "for i in range(len(nums)-2,-1,-1):"

  • @elias043011
    @elias043011 6 месяцев назад

    Having a hard time understanding why [2, 0, 0] would work with the greedy solution... if you look left of the final 0, would it not be possible to reach the final item?

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

    11:10, a walk trhough of the negative case would've been great