Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

public static int[] rotateLeft(int[] a, int n) { int[] temp = new int[a.length];

ID: 3771373 • Letter: P

Question

public static int[] rotateLeft(int[] a, int n)
{
int[] temp = new int[a.length];
  

return temp;
}

Complete this method

Java Array

This method takes in a reference to an integer array and a
positive integer n and it returns a new array whose contents
is the contents of the input array rotated to the left n places.
So each element a[i] of the input array should be placed at
location b[i-n] of the returned array. If the index i-n is
negative, then that index should "wrap" around to the end of
the output array.

For example, if the input array is a = {1, 2, 3, 4, 5}, then
rotateLeft(a, 2) should return an array containing {3, 4, 5, 1, 2}.

This method should not make any changes to the input array.

Explanation / Answer

Please find the required solution

public class RotateLeft {
   public static int[] rotateLeft(int[] a, int n) {
       int[] temp = new int[a.length];
       for (int i = 0; i < a.length; i++) {
           if (i - n <= 0) {
               temp[i] = a[i - n - 1 + a.length];
           } else
               temp[i] = a[i - n - 1];
       }
       return temp;
   }

   public static void main(String[] args) {
       int[] a = { 1, 2, 3, 4, 5 };
       a = rotateLeft(a, 2);
       for (int i = 0; i < a.length; i++)
           System.out.print(a[i] + " ");
   }
}

outout:3, 4, 5, 1, 2