Arrays – Rotate Left

rotate_arrayThis is the first of a set of challenges (I believe the series / set is relatively new) in the HackerRank web site. You may find them at HackerRank under All Domains -> Tutorials -> Cracking the Coding Interview.

The challenge is to develop the body for a method / function that rotates left an array of n integers k times.

My solution (in bold) plus my version of the support code written in Java follows:

import java.util.Scanner;

public class Solution {

/*

* display the array

*/

public static void display(int[] arr) {

for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + ” “);

}

System.out.println();

}

       /*

        * rotate the array of n elements left k times

        */

       public static int[] arrayLeftRotation(int[] a, int n, int k) {

              for (int i= 0; i < k; i++) {

                     int temp = a[0];

                     System.arraycopy(a, 1, a, 0, n – 1);

                     a[n – 1] = temp;

              }

              return a;

       }

/*

* test code

*/

public static void main(String[] args) {

// **** open scanner ****

Scanner sc    = new Scanner(System.in);

// **** read arguments ****

int    n             = sc.nextInt();

int    k             = sc.nextInt();

// **** allocate array ****

int[] arr     = new int[n];

// **** populate array ****

for (int i = 0; i < n; i++) {

arr[i] = sc.nextInt();

}

// **** close the scanner ****

sc.close();

              // **** rotate the array ****

              arr = arrayLeftRotation(arr, n, k);

// **** display the array ****

display(arr);

}

}

Following is a capture of the console in the Eclipse IDE:

5 4

1 2 3 4 5

5 1 2 3 4

The actual solution was accepted by HackerRank.

The challenge is ranked as easy. What I did was to follow the seven steps suggested by Gale McDowell author of “Cracking the Coding Interview” on a video also found in the HackerRank web site. I will comment on the video in a future blog entry. I will continue to solve additional challenges following the steps suggested by Gale McDowell.

If you have comments or questions, please do not hesitate and send me an email message.

John

john.canessa@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *