JavaScript Program for Rotate the matrix right by K times

The term "perform right rotation on a matrix" refers to shifting each column in the matrix to the right. This operation is repeated "k" times when specified. In other words, it's a right shift of the matrix that occurs "k" times. This program can be implemented using various programming languages but a simple yet effective approach is to consider JavaScript for rotating the matrix right by k times.

How to rotate the matrix right by K times?

It is straightforward to carry out a right rotation on a matrix by k times, which involves shifting each column of the matrix to the right by k times. To demonstrate this, let's perform a manual right rotation on a matrix by k times using an example.

Example

Let's take a matrix of size N*M, and a number K. We have to rotate the matrix k times to the right side.

Input matrix: N = 4, M = 4, K = 3
1 2 3 4 
6 7 8 9 
0 9 8 7 
5 4 3 2 

Output matrix:
4 1 2 3
9 6 7 8
7 0 9 8
2 5 4 3

Approach

The process of performing a right rotation k times may seem easy to understand, but it can be a bit challenging to implement. The approach involves copying the elements of each column of the ith row into a temporary array until m-k. Then, we transfer the elements from k to the end to the beginning of the ith row. Finally, we copy the elements back from the temporary array to the end of each ith row of the matrix.

Let's see the algorithm for the approach that we will be using.

Algorithm to rotate the matrix right by K times

STEP 1 ? Determine the number of rows and columns in the matrix.

STEP 2 ? Calculate the number of times each row needs to be shifted based on the value of k. This can be done using the modulus operator (%).

STEP 3 ? For each row in the matrix, create a new array that contains the elements that need to be shifted.

STEP 4 ? Use the slice() and concat() methods to create the rotated row.

STEP 5 ? Set the original row to the new row.

STEP 6 ? Repeat steps 3-5 for each row in the matrix.

Example

In this program, we define a MatrixRotation class that has two static methods: displayMatrix() and rotateMatrixRight().

The displayMatrix() method takes a matrix as input and displays it in the console. It uses a for loop to iterate over each row in the matrix and logs it to the console.

The rotateMatrixRight() method takes a matrix and a number k as input and returns a new matrix that has been rotated to the right by k positions. It uses array slicing to perform the rotation efficiently.

class MatrixRotation {
   static displayMatrix(matrix) {
      for (let i = 0; i < matrix.length; i++) {
         console.log(matrix[i]);
      }
   }
   
   static rotateMatrixRight(matrix, k) {
      const numRows = matrix.length;
      const numCols = matrix[0].length;
      
      // Calculate the number of times each row needs to be shifted
      const shifts = k % numCols;
      
      // Rotate each row of the matrix
      for (let i = 0; i < numRows; i++) {
         const row = matrix[i];
         // Create a new row that contains the shifted elements
         const newRow = row.slice(numCols - shifts).concat(row.slice(0, numCols - shifts));
         // Set the original row to the new row
         matrix[i] = newRow;
      }
      return matrix;
   }
}

// Example usage
const inputMatrix = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
const k = 2;

console.log("Input matrix:");
MatrixRotation.displayMatrix(inputMatrix);

const outputMatrix = MatrixRotation.rotateMatrixRight(inputMatrix, k);

console.log("Output matrix:");
MatrixRotation.displayMatrix(outputMatrix);
Input matrix:
[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]
Output matrix:
[ 2, 3, 1 ]
[ 5, 6, 4 ]
[ 8, 9, 7 ]

How It Works

The key insight is that rotating a row to the right by k positions is equivalent to taking the last k elements and moving them to the front. We use array slicing:

  • row.slice(numCols - shifts) gets the last 'shifts' elements
  • row.slice(0, numCols - shifts) gets all elements except the last 'shifts'
  • concat() joins them to create the rotated row

Alternative Approach - Creating a Copy

If you want to preserve the original matrix, here's a version that creates a new matrix:

function rotateMatrixRightCopy(matrix, k) {
   const numRows = matrix.length;
   const numCols = matrix[0].length;
   const shifts = k % numCols;
   
   // Create a new matrix to store the result
   const rotatedMatrix = [];
   
   for (let i = 0; i < numRows; i++) {
      const row = matrix[i];
      const newRow = row.slice(numCols - shifts).concat(row.slice(0, numCols - shifts));
      rotatedMatrix.push(newRow);
   }
   
   return rotatedMatrix;
}

// Example with original matrix preserved
const originalMatrix = [
   [1, 2, 3, 4],
   [5, 6, 7, 8]
];

console.log("Original matrix:");
console.log(originalMatrix);

const rotatedCopy = rotateMatrixRightCopy(originalMatrix, 1);
console.log("Rotated matrix (copy):");
console.log(rotatedCopy);
Original matrix:
[ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]
Rotated matrix (copy):
[ [ 4, 1, 2, 3 ], [ 8, 5, 6, 7 ] ]

Conclusion

A right rotation on a matrix by k times can be achieved using array slicing and concatenation in JavaScript. The key is to use the modulus operator to handle cases where k is larger than the number of columns, and then slice each row appropriately to move the last k elements to the front.

Updated on: 2026-03-15T23:19:01+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements