pantpuneet.com Blog


Left rotate an array to k places

Posted in Uncategorized by Administrator on the March 4th, 2018

package com.pnp.array.operations;

public class RorateArray {

public static int[] arrayLeftRotation(int[] nums, int n, int k) {
if(k > nums.length)
k=k%nums.length;

int[] result = new int[nums.length];
int j=0;
for(int i=k;i<nums.length;i++){
result[j]=nums[i];
j++;
}

//System.out.println(j);
for(int i=0;i<k;i++){
result[j]=nums[i];
j++;
}

return result;
}

public static void main(String[] args) {
int numbers[] = new int[]{1,2,3,4,5,6};
int k=4;//no. of places to rotate
int n=numbers.length;

int[] output = new int[n];

output = arrayLeftRotation(numbers, n, k);
for(int i = 0; i < n; i++)
System.out.print(output[i] + ” “);

}

/* Output:
* when k=3, output=4 5 6 1 2 3
* when k=4, output=5 6 1 2 3 4
*/

}

Leave a Reply