Reputation: 505
I try to find a more optimized solution for the HackerRank problem "Arrays: Left Rotation", so I converted array of int primitives to an array of Integers and used the method Collections.rotate. On the first line, the user enters the n = number of integers,then k = number of left rotations and, on the second line, the user enters n space-separated integers.
But when it was tested with the following input:
61 48
431 397 149 275 556 362 852 789 601 357 516 575 670 507 127 888 284 405 806 27 495 879 976 467 342 356 908 750 769 947 425 643 754 396 653 595 108 75 347 394 935 252 683 966 553 724 629 567 93 494 693 965 328 187 728 389 70 288 509 252 449
The output turned out to be different than expected. My code is the following:
public class HackerRankArraysLeftRotationOptimized {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // the number of integers
int k = in.nextInt(); // the number of left rotations you must perform
int a[] = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
Integer[] newArray = new Integer[a.length];
int i = 0;
for (int value: a) {
newArray[i++] = Integer.valueOf(value);
}
for (int j = 0; j < k; j++) {
Collections.rotate(Arrays.asList(newArray), k);
}
for (int m = 0; m < newArray.length; m++) {
System.out.print(newArray[m] + " ");
}
}
}
Could someone explain me what's wrong with the method Collections.rotate?
Upvotes: 3
Views: 150
Reputation: 5592
Collections.rotate() is rotating to the right, that's the first problem. Second problem is you are rotating by k
in a loop, so you are totating k*k
times. You just need to do this (not in a loop):
Collections.rotate(Arrays.asList(newArray), -k);
Upvotes: 1