Rotate Array to the Right
Problem
Read an array and a number k. Rotate the array to the right by k places. Print the new array. k can be larger than n. Example: 1 2 3 4 5 6 7 with k = 3 gives 5 6 7 1 2 3 4.
Constraints
- 1 <= n <= 10^5
- 0 <= k <= 10^9
Examples
Input
7 1 2 3 4 5 6 7 3
Output
5 6 7 1 2 3 4
Solutions
Three reversals rotate an array in place: reverse all, then reverse the first k, then reverse the rest. No extra array is needed.
/*
* Problem : Process an array and a number k.
* Input : n, then n integers, then k.
* Output : The rotated array.
* Approach: Three reversals.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method reverses the part of the array from index "from" to index "to".
static void reverse(int[] a, int from, int to) {
while (from < to) {
int temporary = a[from];
a[from] = a[to];
a[to] = temporary;
from++;
to--;
}
}
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a, int k) {
// Step 1: Rotating by n places gives the same array, so only k % n matters.
int n = a.length;
k = k % n;
// Step 2: Reverse the whole array. Example: 1234567 -> 7654321.
reverse(a, 0, n - 1);
// Step 3: Reverse the first k elements. 7654321 -> 5674321.
reverse(a, 0, k - 1);
// Step 4: Reverse the other elements. 5674321 -> 5671234.
reverse(a, k, n - 1);
return a;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int k = scanner.nextInt();
System.out.println(Arrays.stream(solve(a, k)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- What does reversing the whole array do to the last k elements?