2

I'm solving this leetcode problem (problem no:55):

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.**

Return true if you can reach the last index, or false otherwise.

Example 1:

Input: nums = [2,3,1,1,4]

Output: true

Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

When I submit the code with the commented out for loop, this is running till 75 test cases out of 170 , and says 'Time limit exceeded' as this code is slower. But when I commented out and replaced with the current for loop, it runs faster and says '70% faster than all python submission in leetcode'.

Both for loops looks similar and run the same number of iterations. Why is one faster than the other?

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        i = 0
        n = len(nums)
        next = None
        
        if(n==1):
            return True
        
        while(i < n):
            ni = nums[i]
            
            if(ni==0):
                return False
            
            if(i==(n-1)):
                break           
            
            max = 0

            # for j in range(ni):
            #     imb = i+j+1+nums[i+j+1]
            #     if(max<imb):
            #         max = imb
            #         next = i+j+1
            #
            #     if(max >= (n-1)):
            #         return True

            for j in range(i, i+nums[i]+1):
                if j+(nums[j]) >= max: 
                    max = j+(nums[j])
                    next = j

                if(max >= (n-1)):
                    return True

            i = next
        
        return False
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    I can't help but notice that the second loop short-circuits *both* inner and outer loops (by `return`ing) when `max >= n-1`, where the first loop can never short-circuit. I can't be bothered to follow the logic to see if the two are equivalent, behavior-wise, but it seems fairly obvious that code that does similar work but one version can short-circuit and the other can't, will run faster if short-circuiting is common. Either that, or you messed up the indentation, and `if(max >= (n-1)): return True` should have been outside the `for` loop. – ShadowRanger Oct 19 '22 at 01:48
  • @ShadowRanger Thanks for looking this and responding , but i have edited the code with comments , so the if(max >= (n-1)): return True return is same for both for loops.I have added the starting and ending of the second for loop. – Adhithya Kiran Oct 19 '22 at 01:53
  • I don't speak Python but it certainly looks like the slow version executes the conditional code more often than the fast version. – Loren Pechtel Oct 19 '22 at 02:24
  • For the first one, the inner loop body depended on the outside variable `i`, making python hard to optimize the loop. And it is worth noting, their time complexity is the same. It is just the optimizer's result difference. – Xin Cheng Oct 19 '22 at 02:46
  • 1
    The first loop is not equivalent to the second one. The first one begins to evaluate ```i+1+nums[i+1]``` but the second one begins to evaluate ```i+nums[i]```, for example. It's meaningless to compare them. – relent95 Oct 19 '22 at 07:30
  • @relent95 , it is same , it is referring to the same index in th array – Adhithya Kiran Oct 19 '22 at 11:08
  • @XinCheng Thank you , i got a new lesson learned today – Adhithya Kiran Oct 19 '22 at 11:09
  • @Adhithya Kiran, You mean ```1+nums[1]``` is the same as ```0+nums[0]``` when i = 0 for example? That's obviously not true. – relent95 Oct 19 '22 at 11:31

0 Answers0