Open In App

JavaScript Program to Find Circular Rotation of an Array by K Positions

Last Updated : 13 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of integers and an integer K, rotate the array to the right by K positions in a circular manner.

Examples: 

Input: nums = [1, 2, 3, 4, 5], k=2
Output: [4, 5, 1, 2, 3]

Input:  nums = [6, 7, 8, 9, 10], k=1
Output: [10, 9, 6, 7, 8]

Below are the approaches to finding the Circular rotation of an array by K positions which are as follows:

Using Extra Space

We first copy the last K elements of the array into a separate array and then shift the remaining elements of the original array to the right by K positions and in the last we copy the rotated elements back into the original array.

Example: Implementation of program to Find Circular rotation of an array by K positions using Extra Space

JavaScript
let nums = [1, 2, 3, 4, 5];
let k = 2;

function rotate(nums, k) {
    const rotation = nums.slice(-k);
    nums.splice(-k);
    nums.unshift(...rotation);
    return nums;
}

rotate(nums, k);
console.log(nums);

Output
Original Array: [ 1, 2, 3, 4, 5 ]
Circularly rotated Array: [ 4, 5, 1, 2, 3 ]

Time Complexity: O(n), where ?n is the number of elements in the array.

Auxiliary Space: O(k), where K is the number of elements to rotate.

Reverse Technique

In this approach, we use the reverse technique to rotate the array circularly by k positions to the right. It first reverses the entire array, then reverses the first k elements, and finally reverses the remaining elements.

Example: Implementation of program to Find Circular rotation of an array by K positions using Reverse Technique.

JavaScript
function reverse(arr, start, end) {
    while (start < end) {
        const temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

function rotateCircularly(arr, k) {
    const n = arr.length;
    reverse(arr, 0, n - 1);
    reverse(arr, 0, k - 1);
    reverse(arr, k, n - 1);
    return arr;
}

const arr = [1, 2, 3, 4, 5];
const k = 2;
console.log("Original Array:", arr);
console.log("Circularly rotated Array:", rotateCircularly(arr, k));

Output
Original Array: [ 1, 2, 3, 4, 5 ]
Circularly rotated Array: [ 4, 5, 1, 2, 3 ]

Time Complexity: O(N),where ?n is the number of elements in the array

Auxiliary Space: O(1)


Next Article

Similar Reads