Rotate the array to the right by k steps in JavaScript

Nilesh Saini
1 min readMay 28, 2022

--

Different approaches to solve the problem

Photo by Zeke Tucker on Unsplash

Approach 1: Naive approach will be to take k elements from the back of the array (pop) and add them to the front (unshift).

  1. Use Splice to remove k elements from the end of the array.
  2. Use unshift and spread operator to add them to the beginning of the array.
  3. Return the array.

Approach 2: Reversal Algorithm

  1. This function will accept an array and a number (k) as an argument.
  2. 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)

--

--

Nilesh Saini
Nilesh Saini

Written by Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube

No responses yet