Assume that n < size of the array.
Example:
Input Array : {1, 2, 3, 4, 5, 6, 7, 8} Input n : 2 Output : {7, 8, 1, 2, 3, 4, 5, 6}
The key here is to take the last n
elements and add them to the beginning. This can be done in following steps.
1. Copy last n
elements to a temporary array
.
2. Shift all the elements in an input array
to the right by n
positions.
3. Insert all the elements from the temporary array
to the beginning of the input array
.
public static int[] rotate(int[] a, int m) { }
C
Java
Python