Rotate the array to the right by k steps in JavaScript
1 min readMay 28, 2022
Different approaches to solve the problem
Approach 1: Naive approach will be to take k elements from the back of the array (pop) and add them to the front (unshift).
- Use Splice to remove k elements from the end of the array.
- Use unshift and spread operator to add them to the beginning of the array.
- Return the array.
Approach 2: Reversal Algorithm
- This function will accept an array and a number (k) as an argument.
- Break the array into two parts A and B.
- Let the length of the array be n
- A: array from index 0 to n - k - 1
- B: array from index n-k to n-1
3. Reverse both A and B individually, Now you have Ar and Br (r: reverse)
4. Now reverse the entire array. (ArBr)r
5. Return the array.
Time Complexity: O(n)
Space Complexity: O(1)