Right circular rotation on an array of integers

Algorithm to perform right circular rotation on an array of integers

One rotation operation moves the last array element to the first position and shifts all remaining elements right one.

Example

Input 
var arr = [4,5,6];
var k = 2;

Output
           k = 1      k = 2    
[4,5,6] -> [6,4,5] -> [5,6,4]

1. Brute Force Method (Naive Approach) O(k)

Simplest way to solve this is to remove the last element from the array and add it on the first.
We can do this with Array, As JavaScript has an inbuilt array method for this.

function circularArrayRotation(arr, k) {
   //Perform the operations k times
    for(let i = 0; i < k; i++){
        arr.unshift(arr.pop());
    }    
    return arr;
}

console.log(circularArrayRotation([4,5,6], 2));
console.log(circularArrayRotation([4,5,6], 3));
Output:
[4, 5, 6] -> [6, 4, 5] -> [5, 6, 4]
[4, 5, 6] -> [6, 4, 5] -> [5, 6, 4] -> [4, 5, 6]

Time complexity: O(k).
Space complexity: O(1).

Explanation

  • We remove the last element by arr.pop() and add it on the first by arr.unshift(), builtin JavaScript array functions.

Time and Space complexity

  • As Array.pop() and Array.unshift() are inbuilt array function they take O(1) time and we are performing these operations k time so Time complexity is O(K)
  • We are not utilizing any extra space so Space Complexity is O(1)

Comments

  • var arr = [4,5,6];
    var k = 1;

    function rotateArr(arr,k) {
    return […arr.slice(k,arr.length),…arr.slice(0,k)]
    }

    console.log(rotateArr(arr,k))

    My Solution for right rotation

Leave a Reply

Your email address will not be published. Required fields are marked *