Blogs
Array Rotation in JavaScript

# Array Rotation in JavaScript

Array rotation, also known as circular shifting, involves shifting the elements of an array by a specified number of positions. This shifting can be done either towards the left or the right. Imagine a circular arrangement of elements, like a ring, where you can rotate the elements around the circle.

### Why is Array Rotation Important?

Array rotation is a useful operation in various programming scenarios. For instance, it can be used to implement circular queues, implement cyclic algorithms, and perform data manipulations. Understanding array rotation is essential for programmers working with data structures and algorithms.

### Implementing Array Rotation in JavaScript

JavaScript provides several methods for implementing array rotation. Here, we'll explore two popular approaches

### Step-by-Step Approach

#### Brute Force Method Code

JavaScript
``````function rotateArrayBruteForce(array, rotations) {
let counter = 0;

while (counter < rotations) {
for (let i = array.length - 1; i > 0; i--) {
const temp = array[i];
array[i] = array[i - 1];
array[0] = temp;
}

counter++;
}
}``````

#### Brute Force Method Steps

• Initialize a counter variable counter to track the number of rotations performed.
• Inside the while loop, iterate through the array in reverse order, starting from the last element.
• For each element, temporarily store the current value in a variable temp.
• Shift the value of the current element to the previous position.
• Finally, assign the stored value (temp) to the first position of the array.
• Increment the counter variable.
• Repeat steps 2-6 until the counter reaches the desired number of rotations (rotations).

#### Optimized Method Code (Reversal Method)

JavaScript
``````function rotateArrayReversalMethod(array, rotations) {
const n = array.length;
reverse(array, 0, n - 1);
reverse(array, 0, n - rotations - 1);
reverse(array, n - rotations, n - 1);
}

function reverse(array, start, end) {
while (start < end) {
const temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}``````

#### Optimized Method Steps

• Initialize a counter variable counter to track the number of rotations performed.
• Inside the while loop, iterate through the array in reverse order, starting from the last element.
• For each element, temporarily store the current value in a variable temp.
• Shift the value of the current element to the previous position.
• Finally, assign the stored value (temp) to the first position of the array.
• Increment the counter variable.
• Repeat steps 2-6 until the counter reaches the desired number of rotations (rotations).

### Time Complexity

• Brute Force Method : O(n^2)
• Optimized Method (Reversal Method) : O(n)

### Space Complexity

• Brute Force Method : O(1)
• Optimized Method (Reversal Method) : O(1)