Learner Level

Implement the jumpGameReachableGreedy method that checks whether the last index is reachable using greedy logic.

The input array nums represents jump power at each index. From index i, you may jump at most nums[i] positions forward.

Your task is to check whether it is possible to reach the last index starting from index 0.

For example, [2,3,1,1,4] returns true because the last index can be reached, but [3,2,1,0,4] returns false because the jump path gets stuck at index 3.

Example 1

Input
nums (int[]) = [2,3,1,1,4]
size (int) = 5
Returns (boolean) true

Example 2

Input
nums (int[]) = [3,2,1,0,4]
size (int) = 5
Returns (boolean) false

Example 3

Input
nums (int[]) = [0]
size (int) = 1
Returns (boolean) true

Track the farthest index that can be reached so far.

Scan the array from left to right. If the current index is greater than the farthest reachable index, you cannot stand on this position, so return false. Otherwise, update the farthest reachable index using i + nums[i].

If the farthest reachable index reaches or passes the last index, return true.

Pseudocode:

function jumpGameReachableGreedy(nums, size):
    farthest = 0
    for i from 0 to size - 1:
        if i > farthest:
            return false
        farthest = max(farthest, i + nums[i])
        if farthest >= size - 1:
            return true
    return true
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.