We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Let me try to explain the method to solve this problem, instead of just giving the code.

When given any array, for example, 1, 3, 7, 8, 6, 5, 4, 2

find each number in ascending order.

find the number 1. it is in the correct position already, no need to move

find the number 2, it should move forward. We just need to move number 2 forward each time by jumping over 2 numbers
array changes to 1, 2, 3, 7, 8, 6, 5, 4

find the number 3, it is already in the correct position after step 2, no need to move

find the number 4, it should also jump over two numbers each time,
array change to 1, 2, 3, 4, 7, 8, 6, 5

after jumping number 5, array change to 1, 2, 3, 4, 7, 5, 8, 6 (jumping over 8, 6 only)

for step 5, swap 7, 5, 8 to change to 1, 2, 3, 4, 5, 8, 7, 6

find number 6, and jump it to change array to 1, 2, 3, 4, 5, 6, 8, 7

this result shows the array could not be ordered finally, return "NO".

For the above step b, think about why we should make the number 2 jump over two numbers every time. That is the key of the question.

Cookie support is required to access HackerRank

Seems like cookies are disabled on this browser, please enable them to open this website

## Larry's Array

You are viewing a single comment's thread. Return to all comments →

Let me try to explain the method to solve this problem, instead of just giving the code.

When given any array, for example, 1, 3, 7, 8, 6, 5, 4, 2

find each number in ascending order.

find the number 2, it should move forward. We just need to move number 2 forward each time by jumping over 2 numbers array changes to 1, 2, 3, 7, 8, 6, 5, 4

find the number 3, it is already in the correct position after step 2, no need to move

find the number 4, it should also jump over two numbers each time, array change to 1, 2, 3, 4, 7, 8, 6, 5

after jumping number 5, array change to 1, 2, 3, 4, 7, 5, 8, 6 (jumping over 8, 6 only)

for step 5, swap 7, 5, 8 to change to 1, 2, 3, 4, 5, 8, 7, 6

find number 6, and jump it to change array to 1, 2, 3, 4, 5, 6, 8, 7

this result shows the array could not be ordered finally, return "NO".

For the above step b, think about why we should make the number 2 jump over two numbers every time. That is the key of the question.