Search This Blog

Sunday, November 18, 2018

Rotate an array of n elements to the right by k steps.

For example, with n = 6 and k = 2, the array [1,2,3,4,5,6] is rotated to [5,6,1,2,3,4].

1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Reverse first part: 4,3,2,1,5,6
3. Reverse second part: 4,3,2,1,6,5
4. Reverse the whole array: 5,6,1,2,3,4