Thursday, September 4, 2025
HomeData Modelling & AIJavascript Program to Print array after it is right rotated K times

Javascript Program to Print array after it is right rotated K times

Given an Array of size N and a values K, around which we need to right rotate the array. How to quickly print the right rotated array?
Examples : 
 

Input: Array[] = {1, 3, 5, 7, 9}, K = 2.
Output: 7 9 1 3 5
Explanation:
After 1st rotation - {9, 1, 3, 5, 7}
After 2nd rotation - {7, 9, 1, 3, 5}

Input: Array[] = {1, 2, 3, 4, 5}, K = 4.
Output: 2 3 4 5 1      

 

Approach:
 

  1. We will first take mod of K by N (K = K % N) because after every N rotations array will become the same as the initial array. 
     
  2. Now, we will iterate the array from i = 0 to i = N-1 and check, 
    • If i < K, Print rightmost Kth element (a[N + i -K]). Otherwise, 
       
    • Print array after ‘K’ elements (a[i – K]). 
       

Below is the implementation of the above approach. 
 

Javascript




// Javascript implementation of right rotation
// of an array K number of times
  
// Function to rightRotate array
function RightRotate(a, n, k)
{
  
    // If rotation is greater
    // than size of array
    k = k % n;
  
    for (let i = 0; i < n; i++) {
        if (i < k) {
  
            // Printing rightmost
            // kth elements
            document.write(a[n + i - k] + " ");
        }
        else {
  
            // Prints array after
            // 'k' elements
            document.write((a[i - k]) + " ");
        }
    }
    document.write("<br>");
}
  
// Driver code
let Array = [1, 2, 3, 4, 5];
let N = Array.length;
let K = 2;
  
RightRotate(Array, N, K);
  
// This code is contributed by gfgking.


Output: 

4 5 1 2 3

 

Time complexity : O(n) 
Auxiliary Space : O(1)
 

Please refer complete article on Print array after it is right rotated K times for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32263 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11857 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS