How to use Temp Array and copy In Javascript
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.
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));
Output
rotated array is [ 4, 5, 1, 2, 3 ]
Time complexity : O(n)
Space complexity : O(k)
Rotate an Array to the Left by K Steps using JavaScript
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:
Table of Content
- Using Temp Array and copy
- Using Array Splice and Push
- Using Slice and Concatenation