Faaez Razeen

Jump Game

  • 2 min read
  • Greedy
  • LC-Medium
  • Dynamic Programming

3 years ago

Greedy Solution

There are a lot of overlapping subproblems, so it makes sense to use dynamic programming here. However, it still TLEs on Leetcode.

TimeSpaceExplanation
O(n)O(1)
def canJump(self, nums: List[int]) -> bool: goal = len(nums) - 1 for i in range(len(nums) - 2, -1, -1): if i + nums[i] >= goal: goal = i return goal == 0

Dynamic Programming Solution (TLE)

There are a lot of overlapping subproblems if we do the typical logic of looking at the first index, looking at it's value, and travelling to all the index we can travel from it and checking them individuallyw, so it makes sense to use dynamic programming here. However, it still TLEs on Leetcode.

TimeSpaceExplanation
O(n^2)O(n)
def canJump(self, nums: List[int]) -> bool: memo = {} def dfs(i): if i in memo: return memo[i] if i == len(nums) - 1: return True if nums[i] == 0: return False can_jump = False for jump in range(1, nums[i] + 1): can_jump = can_jump or dfs(i + jump) memo[i] = can_jump return can_jump return dfs(0)