How to Rotate an Array in Java

ateevduggal

Ateev Duggal

Posted on May 31, 2022

How to Rotate an Array in Java

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]
Enter fullscreen mode Exit fullscreen mode

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] 
Enter fullscreen mode Exit fullscreen mode

How to solve it

There are many kinds of approaches, but we will only be seeing two approaches in this blog They are –

  1. Using the temp array
  2. 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

  1. Store the first k elements in a temp array: temp[] = [1, 2]
  2. Shift rest of the elements(according to the given data/ question): arr[] = [3, 4, 5,]
  3. Store back the k elements: arr[] = [3, 4, 5, 1, 2]

Continue Reading.

💖 💪 🙅 🚩
ateevduggal
Ateev Duggal

Posted on May 31, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related