![]() |
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 There are several approaches to Rotate an array to the left by k steps using JavaScript which are as follows: Using Temp Array and copyTo 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.
Output rotated array is [ 4, 5, 1, 2, 3 ] Time complexity : O(n) Space complexity : O(k) Using Array Splice and PushTo 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.
Output rotated array is [ 4, 5, 1, 2, 3 ] Time complexity : O(n) Space complexity : O(n) Using Slice and ConcatenationTo 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.
Output rotated array is : [ 4, 5, 1, 2, 3 ] Time complexity : O(n) Space complexity : O(n) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |