Learn DSA
Two Pointers
Sliding Window
Intervals
Stack
Linked List
Binary Search
Heap
Depth-First Search
Breadth-First Search
Backtracking
Graphs
Dynamic Programming
Greedy Algorithms
Trie
Prefix Sum
Matrices
Jump Game
DESCRIPTION (credit Leetcode.com)
Write a function to determine whether you can travel from the first index to the last index of an integer array nums, where each number in the array specifies the maximum distance you can jump from that index. The function should return true if reaching the last index is possible, and false otherwise.
EXAMPLES
Input:
nums = [1, 3, 0, 1, 4]
Output:
true
Explanation: You can jump from index 0 to index 1, then jump from index 1 to index 4 which is the last index.
Example: Input:
nums = [2,2,1,0,5,1,1]
Output:
false
Explanation: The first three indexes take you to index 3 no matter what. But you cannot move beyond index 3 because its maximum jump length is 0, making the indexes after index 3 unreachable.
Solution
def canJump(nums):max_reach = 0for i in range(len(nums)):if i > max_reach:return Falsemax_reach = max(max_reach, i + nums[i])return True
Explanation
Returning False
def canJump(nums):max_reach = 0for i in range(len(nums)):if i > max_reach:return Falsemax_reach = max(max_reach, i + nums[i])return True
Time Complexity
- Time Complexity: O(n) where n is the length of the input array nums.
- Space Complexity: O(1) since we are using a constant amount of space.
Loading comments...