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
jump game
0 / 12
1x
Explanation
We can solve this problem using a greedy approach. We'll iterate through the array, and greedily see how far we can reach if we were to jump from that index. We'll use a variable max_reach that stores the maximum index we can reach using the indexes we have visited so far.
If at any point, the current index is greater than max_reach, then we return false because we would never be able to reach that index from the previous indexes, which thus makes it impossible to reach the end of the array.
Otherwise, we update max_reach to be the maximum of max_reach and i + nums[i] (representing the maximum index we can reach from the current index), and continue iterating through the array. If we reach the end of the array, then we return true.
Returning False
Here's an example of an input array that would return false. We can reach index 3, but since the maximum jump length at index 3 is 0, we can't reach anything beyond that.
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
jump game
0 / 11
1x
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.
© 2024 Optick Labs Inc. All rights reserved.
Loading comments...