JUMP GAME

Moderate
0/80
Average time to solve is 40m
2 upvotes
Asked in companies
WalmartTata Consultancy Services (TCS)Groww

Problem statement

Given an array of non-negative integers ‘ARR’ of length ‘N’, you are initially positioned at the array's first index.

Each element in the array represents your maximum jump length at that position.

Return the minimum number of jumps required to reach the last index.

If it is not possible to reach the last index, return -1.

Example:
Input:

‘N’ = 3
‘ARR’ = [ 2, 1, 1 ]

The shortest way to reach index 2 is
Index 0 => Index 2
that requires only 1 jump.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains ‘T,’ denoting the number of test cases.

The first line of each test case contains ‘N’ denoting the size of the ‘ARR’.

The second line of each test case contains 'N' space-separated Integers denoting the ‘ARR’.
Output Format:
For each test case, Return the answer as described in the problem statement.

Output for each test case is printed on a separate line.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10    
1 <= N <= 10000
0 <= ARR [ i ] <= N
Time Limit: 1 sec
Sample Input 1:
2
5
2 3 1 1 4
4
1 1 1 1

Sample Output 1:

2
3
Explanation Of Sample Input 1:
For the first test case:-
The optimal path is:
0 => 1 => 4

For the second test case:-
0 => 1 => 2 => 3
Sample Input 2:
2
5
2 3 0 1 4
3
1 0 2    
Sample Output 2:
2
-1
Hint

Can we use dynamic programming here?

Approaches (2)
optimized brute force

We can use dynamic programming. We can build an array ‘DP’ of size ‘N’ where

DP [ i ] denotes the minimum number of jumps to reach index ‘i’ from index 0.

 

We can traverse the array from left to right for every index ‘i’ from 0 to ‘N’ - 1. For every index ‘i’,  we can iterate from index ‘i’ + 1 to + ‘i’ + ARR [ i ], updating the values if jumping from index ‘i’ is more optimal.

 

The steps are as follows:-

 

function minJumps ( int N , [ int ] ARR ):

  1. Initialise an array ‘DP’ of the size of ‘N’ with -1.
  2. Initialise DP [ 0 ] with 0.
  3. Run a loop from ‘i’ =0 to ‘N’ -1:
    • Run a loop from ‘j’ =’i’ + 1 to ‘i’ + ARR [ i ]:
      • If DP [ i ] is not -1 and either  DP [ i ] + 1 < DP [ j ] or DP [ j ] is -1
        • DP [ j ] = DP [ i ] + 1.
  4. Return DP [ N - 1 ].
Time Complexity

O (  N2  ), Where ‘N’ is the size of array ‘ARR’.

 

We are running a nested for loop with at most N X N steps in total.

 

Hence, the time complexity is O (  N).

Space Complexity

O ( N ).

 

We are using extra space to make the ‘DP’ array.
 

Hence, the space complexity is O ( N ).

Code Solution
(100% EXP penalty)
JUMP GAME
Full screen
Console