In this blog, we will learn what exactly array rotation is? And how to rotate an array either in the left or the right direction. Here rotation only means shifting the elements of the array in the desired direction.
Example
Input : Arr[] = [1, 2, 3, 4, 5]
k = 2
OutPut : Arr[] = [4, 5, 1, 2, 3]
Explanation
Initially, the array was [1, 2, 3, 4, 5], if we rotate the array once (k=1) towards the right, the element will shift from the index 0 to index 1 Similarly, we need to shift all elements towards the right, which means the last element will end up with at the first position.
Now after the first rotation – Arr[] = [5, 1, 2, 3, 4]
If we rotate on more time – Arr[] = [4, 5, 1, 2, 3] - k = 2
Similarly, if we want to rotate the array towards the left. In that case, we have to shift the elements to the left, the element will shift from index 1 to index 0, and the other elements as well making the first element the last element of the array.
Input : Arr[] = [1, 2, 3, 4, 5]
k = 2
Output : Arr[] = [3 4 5 1 2]
How to solve it
There are many kinds of approaches, but we will only be seeing two approaches in this blog They are –
- Using the temp array
- By reversing the Array
Approach 1 – By using the Temp Array
The idea is simple, we will create a new array of size k and store the elements equal to k from either start or the end of the array depending upon the type of rotation we are doing, and then put them back in the original array where they were supposed to be placed after rotation. Check the example given below in which we are rotating k times towards left, to understand the approach better.
Example
Input arr[] = [1, 2, 3, 4, 5]
k = 2
- Store the first k elements in a temp array: temp[] = [1, 2]
- Shift rest of the elements(according to the given data/ question): arr[] = [3, 4, 5,]
- Store back the k elements: arr[] = [3, 4, 5, 1, 2]
Top comments (0)