Rotate an Array to the Left by K Steps using JavaScript
Last Updated :
04 Apr, 2024
JavaScript allows us to rotate an array to the left by k steps. One can give an input array to rotate it in the left direction by giving k steps. Let’s see an example to understand the problem.
Example:
Input
array = [ 1 , 2 , 3 , 4 , 5]
k = 3
Output
array = [ 4, 5 , 1, 2 , 3]
There are several approaches to Rotate an array to the left by k steps using JavaScript which are as follows:
Using Temp Array and copy
To handle the case when k is greater than length of array , we will calculate k modulo the length of the array. Now we Copy the first k elements into the temp array. Shift n-k elements from last by k positions to the left. Copy the elements from the temp array into the main array. Return the modified array.
Example: To demonstrate Rotation of an array to the left by k steps using Temp Array and copy.
JavaScript
function rotateLeft(arr, k) {
const n = arr.length;
k %= n;
const temp = arr.slice(0, k);
// Shift n-k elements from last by k positions to the left
for (let i = k; i < n; i++) {
arr[i - k] = arr[i];
}
// Copy the elements
for (let i = 0; i < k; i++) {
arr[n - k + i] = temp[i];
}
return arr;
}
const array = [1, 2, 3, 4, 5];
const k = 2;
console.log("rotated array is ", rotateLeft(array, k));
Outputrotated array is [ 4, 5, 1, 2, 3 ]
Time complexity : O(n)
Space complexity : O(k)
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 then splice is used to remove the first k elements from the array, which are then pushed to the end using push method. which then return the modified array.
Example: To demonstrate Rotation of an array to the left by k steps using array splice and push.
JavaScript
function rotateLeft(arr, k) {
k %= arr.length;
// To handle cases where k > array length
arr.push(...arr.splice(0, k));
return arr;
}
let array = [1, 2, 3, 4, 5];
let k = 3;
console.log("rotated array is", rotateLeft(array, k));
Outputrotated array is [ 4, 5, 1, 2, 3 ]
Time complexity : O(n)
Space complexity : O(n)
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 then slice is used to extract the elements from index k to the end of the array and concatenate them using concat() with the elements from the beginning of the array to index k returning the result.
Example: To demonstrate Rotation of an array to the left by k steps using Slice and concatenation.
JavaScript
function rotateLeft(arr, k) {
k %= arr
.length;
return arr
.slice(k)
.concat(arr.slice(0, k));
}
let array = [1, 2, 3, 4, 5];
let k = 3;
console.log("rotated array is : ", rotateLeft(array, k));
Outputrotated array is : [ 4, 5, 1, 2, 3 ]
Time complexity : O(n)
Space complexity : O(n)
Share your thoughts in the comments
Please Login to comment...