Array Left rotation by k elements one by one

In this article we will see how to left rotate an array by k elements using constant space space O(1) and in O(k*n) time complexity, lets assume the given array is:

Input: int [] arr = {1,2,3,4,5,6,7};
k=3
Output: int [] arr = {4,5,6,7,1,2,3};

Algorithm: Array Rotation

1) Iterate over the array k times.
2) In each loop:
2.1) Store start element in a tmp variable and shift element from 1 to n-1 to the left by 1 place.
2.2) Copy temp element at the end of the array,

k=number of elements to be rotated, i=current element index, n=length of array


	private static void rotate(int[] arr, int n, int k) {

		for (int i = 0; i < k; i++) {
			int tmp = arr[0];
			// shift element left by 1 place
			for (int j = 1; j < n; j++) {
				arr[j - 1] = arr[j];
			}
			arr[n-1] = tmp;
		}
	}
Time complexity : O(n * k)
Auxiliary Space : O(1)


Complete example: Array rotation one by one example in Java

package com.tb.array;

import java.util.Arrays;

public class ArrayRotateLeftOneByOne {

	private static int[] arr = { 1, 2, 3, 4, 5, 6, 7 };

	private static void rotate(int[] arr, int n, int k) {

		for (int i = 0; i < k; i++) {
			int tmp = arr[0];
			// shift element left by 1 place
			for (int j = 1; j < n; j++) {
				arr[j - 1] = arr[j];
			}
			arr[n-1] = tmp;
		}
	}

	public static void main(String[] args) {
		print(arr);

		// rotate by 3
		rotate(arr, arr.length, 3);

		print(arr);
	}

	private static void print(int[] arr) {
		System.out.println();
		Arrays.stream(arr).forEach(System.out::print);
	}
}
Output: Output of above example will look something like this.
1234567
4567123