Rotate an Array to the Right by K Steps using JavaScript
Last Updated :
31 Jul, 2024
One can Rotate an array to the left by k steps using JavaScript. We are given an input array and a value k we have to rotate that array by k steps in the right direction.
Example:
Input
arr = [1 , 2 , 3 , 4 , 5 ]
k = 3
Output
arr = [ 3 , 4 , 5 , 1 , 2]
Below are different approaches to Rotate an array to the left by k steps using JavaScript which are as follows:
Using Reverse Method
To handle the case when k is greater than length of array , we will calculate k modulo the length of the array. Now Reverse the entire array. Reverse the first k elements of the array, where k is number of steps we have to rotate array in right direction. Reverse the remaining elements of the array. Return modified array.
Example: To demonstrate Rotation of an array to the left by k steps using reverse method only
JavaScript
function rotateArrayReverse(nums, k) {
const n = nums.length;
k = k % n;
// Reverse the entire array
nums.reverse();
// Reverse the first k elements
reverseArray(nums, 0, k - 1);
// Reverse the remaining elements
reverseArray(nums, k, n - 1);
return nums;
}
function reverseArray(arr, start, end) {
while (start < end) {
const temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
const nums = [1, 2, 3, 4, 5, 6, 7];
const k = 3;
console.log(rotateArrayReverse(nums, k));
Output[
5, 6, 7, 1,
2, 3, 4
]
Time complexity : O(n)
Space complexity : O(1)
Using Array Splice and Push
To handle the case when k is greater than length of array , we will calculate k modulo the length of the array. Now Use the splice method to remove the last k elements from the array and Push the removed elements at the beginning of the array. Return the modified array.
Example: To demonstrate Rotation of an array to the left by k steps using array splice and push
JavaScript
function rotateArraySplice(nums, k) {
const n = nums.length;
k = k % n;
// Remove the last k
// elements from array
const removed = nums.splice(-k);
// Insert the removed elements
// at starting of the array
nums.unshift(...removed);
return nums;
}
const nums = [1, 2, 3, 4, 5, 6, 7];
const k = 3;
console.log(rotateArraySplice(nums, k));
Output[
5, 6, 7, 1,
2, 3, 4
]
Time complexity : O(k)
Space complexity : O(k)
Using Slice and Concatenation
To handle the case when k is greater than length of array , we will calculate k modulo the length of the array. Now Use the slice() method to extract the last k elements and the remaining elements of the array. Concatenate the sliced parts: Concatenate the sliced parts in reverse order using the concat() method. Return the modified array
Example : To demonstrate Rotation of an array to the right by k steps using array splice and push
JavaScript
function rotateArraySliceConcat(nums, k) {
const n = nums.length;
k %= n;
// Concatenate the sliced parts in reverse order
const rotated = nums.slice(-k).concat(nums.slice(0, n - k));
return rotated;
}
const nums = [1, 2, 3, 4, 5, 6, 7];
const k = 3;
console.log(rotateArraySliceConcat(nums, k));
Output[
5, 6, 7, 1,
2, 3, 4
]
Time Complexity: O(k + m)
Space Complexity: O(k + m)
Using Unshift and Pop Methods
The unshift and pop methods can also be used to rotate an array to the left by k steps. This approach involves repeatedly removing the last element of the array using pop and adding it to the beginning of the array using unshift. This method is straightforward and works well for small values of k.
Example: In this example, we'll rotate an array to the left by k steps using the unshift and pop methods.
JavaScript
function rotateArrayLeft(arr, k) {
k = k % arr.length;
for (let i = 0; i < k; i++) {
let lastElement = arr.pop();
arr.unshift(lastElement);
}
return arr;
}
let arr = [1, 2, 3, 4, 5];
let k = 3;
console.log(rotateArrayLeft(arr, k))
Similar Reads
Javascript Program to Print array after it is right rotated K times Given an Array of size N and a values K, around which we need to right rotate the array. How to quickly print the right rotated array?Examples :Â Â Input: Array[] = {1, 3, 5, 7, 9}, K = 2. Output: 7 9 1 3 5 Explanation: After 1st rotation - {9, 1, 3, 5, 7} After 2nd rotation - {7, 9, 1, 3, 5} Input:
2 min read
How to rotate array elements by using JavaScript ? Given an array containing some array elements and the task is to perform the rotation of the array with the help of JavaScript. There are two approaches that are discussed below: Using Array unshift() and pop() MethodsUsing Array push() and shift() MethodsMethod 1: Using Array unshift() and pop() Me
2 min read
Javascript Program for Rotate the matrix right by K times Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4A simple yet effective approach is to consider
2 min read
Javascript Program for Program to cyclically rotate an array by one Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Following are steps. 1) Store last element in a variable say x. 2) Shift all eleme
2 min read
Javascript Program to Split the array and add the first part to the end | Set 2 Given an array and split it from a specified position, and move the first part of array add to the end.  Examples:  Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1,
2 min read
Javascript Program to Find the Mth element of the Array after K left rotations Given non-negative integers K, M, and an array arr[] with N elements find the Mth element of the array after K left rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1Output: 5Explanation:Â The array after first left rotation a1[ ] = {4, 5, 23, 3}The array after second left rotation a2[ ]
2 min read
Javascript Program for Left Rotation and Right Rotation of a String Given a string of size n, write functions to perform the following operations on a string-Left (Or anticlockwise) rotate the given string by d elements (where d <= n)Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Le
3 min read
Javascript Program to Find Mth element after K Right Rotations of an Array Given non-negative integers K, M, and an array arr[ ] consisting of N elements, the task is to find the Mth element of the array after K right rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1 Output: 5 Explanation: The array after first right rotation a1[ ] = {23, 3, 4, 5} The array a
8 min read
Javascript Program to Count of rotations required to generate a sorted array Given an array arr[], the task is to find the number of rotations required to convert the given array to sorted form.Examples: Input: arr[] = {4, 5, 1, 2, 3}Â Output: 2Â Explanation:Â Sorted array {1, 2, 3, 4, 5} after 2 anti-clockwise rotations. Input: arr[] = {2, 1, 2, 2, 2}Â Output: 1Â Explanation:Â So
4 min read
Find the Rotation Count in Rotated Sorted array in JavaScript A Rotated Sorted Array is an array type in JavaScript that has been rotated to the left or right by some random number of positions. In this article, we will understand how to find the count of rotations performed on the original sorted array to obtain the given sorted array using JavaScript languag
5 min read