Hackerrank jumping on the clouds solution

In this article, you can find the solution for the Hackerrank “jumping on the clouds” challenge. The following section contains the description of the challenge provided by the Hackerrank website:

There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. The player must avoid the thunderheads. Determine the minimum number of jumps it will take to jump from the starting position to the last cloud. It is always possible to win the game.

Based on the given description from the beginning cloud we have 2 options for each state to make, we can go 1 or 2 step forward. Since the target is to find the minimum number of moves to reach the last cloud it is better to try with step size 2 first if possible and then try 1.

The following image describes the steps for a sample input array of different types of clouds. [0,0,1,0,0,1,0]

The output result of this array is number 4 because in the best possible way we need 4 moves to reach the last cloud.

Solution

There are a lot of different approaches to solving this problem. The following is one of the efficient ways to solve it.

public static int jumpingOnClouds2(List<Integer> c) {
int result = 0;
for( int i = 1 ; i < c.size() ; i++){
if( (i+1) < c.size() && c.get(i+1) != 1 ) {
result++;
i++;
continue;
}
if( c.get(i) != 1 ) result++;
}
return result;
}

As you can see in the code on each step from the start we try to move with size 2 first and if it fails the criteria and can not land in a cumulus cloud we try the move with size 1.

We do recommend that before just using the code try to solve the issue yourself and try this checking this solution in case you have failed to pass all the tests.

Hope this article helped you and please support me by your applaud for the story. if you don’t know how it is just like this:

Or buy me a coffee here!

--

--

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Farzin Pashaee

Software Engineer at Maybank, AI and ML enthusiastic