Introduction
An array is a collection of elements of similar data types. We can have an array of integers or characters or structures etc. In this blog, we are going to learn about the circular right rotation of an array. Now you must be wondering what is meant by right rotation!!
The right rotation of an array implies that you have to rotate the array towards the right, i.e., clockwise rotation of an array. This is the most common problem asked by interviewers, so read all the concepts discussed here carefully.
Problem: You are given an array of integers, circularly rotate the array to the right by one.
Let’s understand the problem more clearly with the below example.
Suppose you are given an array arr of integers.
1 |
2 |
3 |
4 |
5 |
6 |
Now you have to rotate the array clockwise by one. So you have to produce output as:-
6 |
1 |
2 |
3 |
4 |
5 |
Now you’re clear with the problem statement so let’s move towards solving it.
Method 1: Using Loops
To rotate the array circularly, we can use loops. Let’s discuss the steps first then we will move towards code.
Step 1: Store the last element of the array in a variable temp.
Step 2: All the elements of the array will be shifted by one towards the right.
Step 3: Replace the first element of the array with the value stored in temp.
Java program for Circular Right Rotation of an Array
import java.util.Arrays;
public class Rotating {
static int arr[] = new int[] {1,2,3,4,5,6};
// Function for rotating the array
static void rotateRight() {
int temp = arr[arr.length - 1];
// Shifting the array elements by one
for (int i = arr.length - 1; i > 0; i--)
arr[i] = arr[i - 1];
// Replacing the first array element by temp
arr[0] = temp;
}
public static void main(String[] args) {
System.out.println("Array given in input is:");
System.out.println(Arrays.toString(arr));
rotateRight();
System.out.println("Array after rotation is:");
System.out.println(Arrays.toString(arr));
}
}
Output:
Array given in input is
1 2 3 4 5 6
Array after rotation is
6 1 2 3 4 5
C++ program for Circular Right Rotation Of an Array
#include <iostream>
using namespace std;
void rotateRight(int * arr, int n) {
int temp = arr[n - 1];
// Shifting the array elements by one
for (int i = n - 1; i > 0; i--)
arr[i] = arr[i - 1];
// Replacing the first array element by temp
arr[0] = temp;
}
int main() {
int arr[] = {1,2,3,4,5,6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array given in input is\n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
rotateRight(arr, n);
printf("\nArray after rotation is\n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output:
Array given in input is
1 2 3 4 5 6
Array after rotation is
6 1 2 3 4 5
Let’s discuss the complexities of method one:
Time Complexity: O(n), where n refers to the number of elements in the array.
You need to iterate through all the elements so time complexity is O(n).
Space Complexity: O(1) As we are not taking any extra space here.