-
Notifications
You must be signed in to change notification settings - Fork 2
/
Array_Rotation.java
58 lines (53 loc) · 1.47 KB
/
Array_Rotation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.company;
import java.io.IOException;
import java.util.Scanner;
public class Array_Rotation {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t-- > 0) {
int n = s.nextInt();
int k = s.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
rotatedArray(n,k,arr);
for (int i = 0; i < arr.length; i++){
System.out.print(arr[i]+" ");
}
}
}
//Brute-Force Approach
private static int[] rotatedArray(int n, int k, int[] arr) {
if(k == 0 || k == n)
return arr;
k = k % n;
rotate(n,k,arr);
return arr;
}
//Brute-Force Approach
private static void rotate(int n, int k, int[] arr) {
int[] front = new int[k];
int[] rear = new int[n - k];
int loc = 0;
for (int i = 0; i < n - k; i++){
rear[loc] = arr[i];
loc++;
}
loc = 0;
for (int i = n - k; i < arr.length; i++){
front[loc] = arr[i];
loc++;
}
for (int i = 0; i < front.length; i++){
arr[i] = front[i];
}
loc = 0;
for (int i = front.length; i < arr.length; i++){
arr[i] = rear[loc];
loc++;
}
}
//Optimized Approach
}