Solved Problem - Rotate Array
In this lesson, we'll see how to rotate an array.
We'll cover the following
Problem statement
Given an array, of length . Rotate it clockwise by or cyclic shift the element to the right by . Input format
The first line consists of two space-separated integers .
The second line consists of space-separated integers representing the array .
Sample
Input:
8 3
1 2 3 4 5 6 7 8
Output
6 7 8 1 2 3 4 5
Solution
Let’s see what happens when we cyclic shift by one. The last element comes to the first place and each other element moves one place to the right. We can do this times. The complexity of this solution would be .
We can optimize it further based on the observation that after operation, the last dd elements become the first elements and the remaining elements each shift to the right by dd places. We can do that in a single go.
Get hands-on with 1400+ tech skills courses.