How to use Array Splice and Push 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 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
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)
Rotate an Array to the Right by K Steps using JavaScript
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:
Table of Content
- Using Reverse Method
- Using Array Splice and Push
- Using Slice and Concatenation