Array Rotation – Left rotation
One of the popular interview topics is Arrays. Its a really simple data structure, that we are using when we started learning programming. But it can really make the interview complex with the discussions associated to it.
A very common interview question of array is rotation of array elements.
Left rotation of Array
Logic 1
Algorithm: leftRotate(input_array, number_of_rotations)
- Create a temporary array with size equal to input array.
- Initialize a count variable to zero.
- Loop through the array elements (step 4- 8):
- Find the index to store elements in temp array.
- tempIndex = count – number_of_rotations
- if tempIndex < 0 then add tempIndex to inputArray.length
- Store input_array[count] to tempArray[tempIndex]
- Increment count by 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static int[] leftRotateArray(int[] arrayToRotate, int numberOfRotations) { int []tempArr = new int[arrayToRotate.length]; int count = 0; while(count<arrayToRotate.length){ int tempIndex = count - numberOfRotations; if(tempIndex<0) tempIndex = tempIndex + arrayToRotate.length; tempArr[tempIndex] = arrayToRotate[count]; count++; } return tempArr; } |
Logic 2
Algorithm: leftRotate(input_array, number_of_rotations)
- input_array[] = [1, 2, 3, 4, 5, 6, 7], number_of_rotations = 2
- Store d elements in a temp array temp[] = [1, 2]
- Shift rest of the input_array[] = [3, 4, 5, 6, 7, 6, 7] to the left.
- Store back the d elements to the end of array. input_array[] = [3, 4, 5, 6, 7, 1, 2]
1 2 3 4 5 6 7 8 |
void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[i] = temp; } |