I have a solution to the HackerRank Circular Array Rotation challenge. It passes 7 test cases out of 15. The rest of them are getting timed out. I think it's because of the huge data set that has been given as the input.
Input Format
The first line contains 3 space-separated integers, n (the length of the array), k (the number of right circular rotations), and q (the number of queries).
The second line contains n space-separated integers a0, a1, a2, …, an-1.
Each of the q subsequent lines contains a single integer denoting m. For each of those queries, output am of the rotated array.Constraints
- 1 ≤ n ≤ 105
- 1 ≤ ai ≤ 105
- 1 ≤ k ≤ 105
- 1 ≤ q ≤ 500
Can you point me out how can I improve this code in order to avoid those time out of test cases?
public class CircularArrayRotation {
public static int[] circularArray(int[] beforeArray){
int[] afterArray = new int[beforeArray.length];
afterArray[0] = beforeArray[beforeArray.length-1];
System.arraycopy(beforeArray,0,afterArray,1,beforeArray.length-1);
return afterArray;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int q = sc.nextInt();
sc.nextLine();
int[] source = new int[n];
String[] elements = sc.nextLine().split(" ");
for (int i=0;i<elements.length;i++){
source[i] = Integer.parseInt(elements[i]);
}
source = repeatCirculating(source,k);
int[] ques = new int[q];
for (int i=0;i<q;i++){
int position = Integer.parseInt(sc.nextLine().trim());
ques[i] = position;
}
for (int ask:ques) {
System.out.println(source[ask]);
}
}
public static int[] repeatCirculating(int[] source, int times){
for (int i =0; i<times; i++){
source = circularArray(source);
}
return source;
}
}