HackerRank Java Arrays- Left Rotation


A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result.

  1. import java.util.Scanner;
  2. // Time Complexity: O(n)
  3. // Space Complexity: O(1) by doing an "in place" rotation
  4. public class Solution {
  5. public static void main(String[] args) {
  6. /* Save input */
  7. Scanner scan = new Scanner(System.in);
  8. int size = scan.nextInt();
  9. int numRotations = scan.nextInt();
  10. int array[] = new int[size];
  11. for (int i = 0; i < size; i++) {
  12. array[i] = scan.nextInt();
  13. }
  14. scan.close();
  15. /* Rotate array (in place) using 3 reverse operations */
  16. numRotations %= size; // to account for numRotations > size
  17. int rotationSpot = size - 1 - numRotations;
  18. reverse(array, 0, size - 1);
  19. reverse(array, 0, rotationSpot);
  20. reverse(array, rotationSpot + 1, size - 1);
  21. /* Print rotated array */
  22. for (int i = 0; i < size; i++) {
  23. System.out.print(array[i] + " ");
  24. }
  25. }
  26. /* Reverses array from "start" to "end" inclusive */
  27. private static void reverse(int[] array, int start, int end) {
  28. if (array == null || start < 0 || start >= array.length || end < 0 || end >= array.length) {
  29. return;
  30. }
  31. while (start < end) {
  32. swap(array, start++, end--);
  33. }
  34. }
  35. private static void swap(int [] array, int i, int j) {
  36. int temp = array[i];
  37. array[i] = array[j];
  38. array[j] = temp;
  39. }
  40. }

download android app