Array Left Rotation K times Algorithm

By   Tewodros   Date Posted: Oct. 1, 2021  Hits: 848   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a list of numbers we want to transform the array by rotating the numbers to left K times.

Example:

A = {1,2,3,4,5} K=1

Ans: {2,3,4,5,1}

Example:

A = {1,2,3,4,5} K=2

Ans: {3,4,5,1,2}

Example:

A = {1,2,3,4,5} K=3

Ans: {4,5,1,2,3}

Explanation:

Rotating the array means moving the elements one position to the left in a circular manner which means the first element becomes the last and everything else shifts to the left

We want to do that for K number of times.

Solution:

Rotating the array K times means we copy all the elements from K to N ,and then elements 0 to K respectively to our result table where N is the size of the array. If  K = N then all the elements will come back to their original place as though no rotation happened or K = 0. 

But this is true if K < N. For larger K values we want to harness the power of modulo operator which is the remainder of the division operation of two number.

In the above example, N = 5

K % 5 = 0 if K = 0

K % 5 = 1 if K = 1

K % 5 = 2 if K = 2

K % 5 = 3 if K = 3

K % 5 = 4 if K = 4

K % 5 = 0 if K = 5

K % 5 = 1 if K = 6 

K % 5 = 2 if K = 7

K % 5 = 0 if K = 10

K % 5 = 0 if K = 15

Do you see that pattern here, K% 5 is always between 0 and K-1 which is exactly how many times we have to rotate the array.

 

 static int[] rotLeft(int[] a, int k)  {       

       int[] result = new int[a.Length];

       int n = a.Length;

       k= k % n;

       int count = 0;

       for (int i = k; i < n; i++)  {

           result[count++] = a[i];

       }

       for (int i = 0; i < k; i++)   {

           result[count++] = a[i];

       }

       return result;

   }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* tuzhzb

Back to Top