Java

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)

  1. Create a temporary array with size equal to input array.
  2. Initialize a count variable to zero.
  3. Loop through the array elements (step 4- 8):
  4. Find the index to store elements in temp array.
  5. tempIndex = count – number_of_rotations
  6. if tempIndex < 0 then add tempIndex to inputArray.length
  7. Store input_array[count] to tempArray[tempIndex]
  8. Increment count by 1.

 

 

Logic 2

Algorithm: leftRotate(input_array, number_of_rotations)

  1. input_array[] = [1, 2, 3, 4, 5, 6, 7], number_of_rotations = 2
  2. Store d elements in a temp array temp[] = [1, 2]
  3. Shift rest of the input_array[] = [3, 4, 5, 6, 7, 6, 7]  to the left.
  4. Store back the d elements to the end of array. input_array[] = [3, 4, 5, 6, 7, 1, 2]

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.