Start learning free

LESSON 502 OF 634 · GREEDY

Jump Game: Reach the End in C++

Practice O(n)

You get a vector nums. You start at index 0.

Return true if you can get to the last index. Otherwise, return false.

From index i, one jump moves you forward by 1 to nums[i] places. You can make as many jumps as you like. From a 0, you can't jump at all.

 

Example 1:

Input: nums = [3,0,2,0,1]
Output: true
Explanation: Jump 2 places, from index 0 to index 2.
Then jump 2 places, from index 2 to index 4.
There, you are on the last index, 4.

Example 2:

Input: nums = [1,3,0,0,0,2]
Output: false
Explanation: From index 0, you can only reach index 1.
From index 1, you can reach indexes 2, 3 and 4.
They all hold 0, so no jump leaves them.
Index 5 stays out of reach.

Example 3:

Input: nums = [0]
Output: true
Explanation: You start on the last index.
No jump is needed.

 

Constraints:

  • 1 to 100,000 numbers.
  • Each number is a whole number from 0 to 100,000.

Note:

Your solution should run in O(n) time and use O(1) extra space.

STEP 1 OF 5
    Ctrl + Enter to check

    Jump Game Reach End in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free