The Wayback Machine - https://web.archive.org/web/20240911091757/https://www.geeksforgeeks.org/rotate-matrix-elements/
Open In App

Rotate Matrix Elements

Last Updated : 27 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a square matrix, the task is to rotate its elements clockwise by one step.

Examples:

Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12

Approaches to Rotate Matrix Elements:

Rotate Matrix Elements using Nested Loops – O(n2) time and O(1) auxiliary space

The idea is to use nested loops to move elements in four directions (right, down, left, and up) one step at a time for each layer starting from the outermost layer. This simulates the clockwise rotation by rotating each “ring” or layer of the matrix.

Code Implementation:

C++
// C++ program to rotate a matrix

#include <bits/stdc++.h>
#define R 4
#define C 4
using namespace std;

// A function to rotate a matrix mat[][] of size R x C.
// Initially, m = R and n = C
void rotatematrix(int m, int n, int mat[R][C])
{
    int row = 0, col = 0;
    int prev, curr;

    /*
    row - Starting row index
    m - ending row index
    col - starting column index
    n - ending column index
    i - iterator
    */
    while (row < m && col < n) {

        if (row + 1 == m || col + 1 == n)
            break;

        // Store the first element of next row, this
        // element will replace first element of current
        // row
        prev = mat[row + 1][col];

        /* Move elements of first row from the remaining
         * rows */
        for (int i = col; i < n; i++) {
            curr = mat[row][i];
            mat[row][i] = prev;
            prev = curr;
        }
        row++;

        /* Move elements of last column from the remaining
         * columns */
        for (int i = row; i < m; i++) {
            curr = mat[i][n - 1];
            mat[i][n - 1] = prev;
            prev = curr;
        }
        n--;

        /* Move elements of last row from the remaining rows
         */
        if (row < m) {
            for (int i = n - 1; i >= col; i--) {
                curr = mat[m - 1][i];
                mat[m - 1][i] = prev;
                prev = curr;
            }
        }
        m--;

        /* Move elements of first column from the remaining
         * rows */
        if (col < n) {
            for (int i = m - 1; i >= row; i--) {
                curr = mat[i][col];
                mat[i][col] = prev;
                prev = curr;
            }
        }
        col++;
    }

    // Print rotated matrix
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++)
            cout << mat[i][j] << " ";
        cout << endl;
    }
}

/* Driver program to test above functions */
int main()
{

    int a[R][C] = { { 1, 2, 3, 4 },
                    { 5, 6, 7, 8 },
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };

    rotatematrix(R, C, a);
    return 0;
}
Java
// Java program to rotate a matrix
import java.lang.*;
import java.util.*;

class GFG {
    static int R = 4;
    static int C = 4;

    // A function to rotate a matrix
    // mat[][] of size R x C.
    // Initially, m = R and n = C
    static void rotatematrix(int m, int n, int mat[][])
    {
        int row = 0, col = 0;
        int prev, curr;

        /*
        row - Starting row index
        m - ending row index
        col - starting column index
        n - ending column index
        i - iterator
        */
        while (row < m && col < n) {

            if (row + 1 == m || col + 1 == n)
                break;

            // Store the first element of next
            // row, this element will replace
            // first element of current row
            prev = mat[row + 1][col];

            // Move elements of first row
            // from the remaining rows
            for (int i = col; i < n; i++) {
                curr = mat[row][i];
                mat[row][i] = prev;
                prev = curr;
            }
            row++;

            // Move elements of last column
            // from the remaining columns
            for (int i = row; i < m; i++) {
                curr = mat[i][n - 1];
                mat[i][n - 1] = prev;
                prev = curr;
            }
            n--;

            // Move elements of last row
            // from the remaining rows
            if (row < m) {
                for (int i = n - 1; i >= col; i--) {
                    curr = mat[m - 1][i];
                    mat[m - 1][i] = prev;
                    prev = curr;
                }
            }
            m--;

            // Move elements of first column
            // from the remaining rows
            if (col < n) {
                for (int i = m - 1; i >= row; i--) {
                    curr = mat[i][col];
                    mat[i][col] = prev;
                    prev = curr;
                }
            }
            col++;
        }

        // Print rotated matrix
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++)
                System.out.print(mat[i][j] + " ");
            System.out.print("\n");
        }
    }

    /* Driver program to test above functions */
    public static void main(String[] args)
    {

        int a[][] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };

        rotatematrix(R, C, a);
    }
}
Python
# Python program to rotate a matrix

# Function to rotate a matrix


def rotateMatrix(mat):

    if not len(mat):
        return

    """
        top : starting row index
        bottom : ending row index
        left : starting column index
        right : ending column index
    """

    top = 0
    bottom = len(mat)-1

    left = 0
    right = len(mat[0])-1

    while left < right and top < bottom:

        # Store the first element of next row,
        # this element will replace first element of
        # current row
        prev = mat[top+1][left]

        # Move elements of top row one step right
        for i in range(left, right+1):
            curr = mat[top][i]
            mat[top][i] = prev
            prev = curr

        top += 1

        # Move elements of rightmost column one step downwards
        for i in range(top, bottom+1):
            curr = mat[i][right]
            mat[i][right] = prev
            prev = curr

        right -= 1

        # Move elements of bottom row one step left
        for i in range(right, left-1, -1):
            curr = mat[bottom][i]
            mat[bottom][i] = prev
            prev = curr

        bottom -= 1

        # Move elements of leftmost column one step upwards
        for i in range(bottom, top-1, -1):
            curr = mat[i][left]
            mat[i][left] = prev
            prev = curr

        left += 1

    return mat

# Utility Function


def printMatrix(mat):
    for row in mat:
        print row


matrix = [
    [1,  2,  3,  4],
    [5,  6,  7,  8],
    [9,  10, 11, 12],
    [13, 14, 15, 16]
]

matrix = rotateMatrix(matrix)
# Print modified matrix
printMatrix(matrix)
C#
// C# program to rotate a matrix
using System;

class GFG {

    static int R = 4;
    static int C = 4;

    // A function to rotate a matrix
    // mat[][] of size R x C.
    // Initially, m = R and n = C
    static void rotatematrix(int m, int n, int[, ] mat)
    {
        int row = 0, col = 0;
        int prev, curr;

        /*
        row - Starting row index
        m - ending row index
        col - starting column index
        n - ending column index
        i - iterator
        */
        while (row < m && col < n) {

            if (row + 1 == m || col + 1 == n)
                break;

            // Store the first element of next
            // row, this element will replace
            // first element of current row
            prev = mat[row + 1, col];

            // Move elements of first row
            // from the remaining rows
            for (int i = col; i < n; i++) {
                curr = mat[row, i];
                mat[row, i] = prev;
                prev = curr;
            }
            row++;

            // Move elements of last column
            // from the remaining columns
            for (int i = row; i < m; i++) {
                curr = mat[i, n - 1];
                mat[i, n - 1] = prev;
                prev = curr;
            }
            n--;

            // Move elements of last row
            // from the remaining rows
            if (row < m) {
                for (int i = n - 1; i >= col; i--) {
                    curr = mat[m - 1, i];
                    mat[m - 1, i] = prev;
                    prev = curr;
                }
            }
            m--;

            // Move elements of first column
            // from the remaining rows
            if (col < n) {
                for (int i = m - 1; i >= row; i--) {
                    curr = mat[i, col];
                    mat[i, col] = prev;
                    prev = curr;
                }
            }
            col++;
        }

        // Print rotated matrix
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++)
                Console.Write(mat[i, j] + " ");
            Console.Write("\n");
        }
    }

    /* Driver program to test above functions */
    public static void Main()
    {

        int[, ] a = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };

        rotatematrix(R, C, a);
    }
}
JavaScript
// Function to rotate the matrix in a clockwise direction
function rotateMatrix(matrix) {
    let m = matrix.length;
    let n = matrix[0].length;
    let row = 0, col = 0;
    let prev, curr;

    /*
    row - Starting row index
    m - ending row index
    col - starting column index
    n - ending column index
    */

    while (row < m && col < n) {

        if (row + 1 === m || col + 1 === n)
            break;

        // Store the first element of the next row, this
        // element will replace the first element of the current row
        prev = matrix[row + 1][col];

        // Move elements of the first row from the remaining rows
        for (let i = col; i < n; i++) {
            curr = matrix[row][i];
            matrix[row][i] = prev;
            prev = curr;
        }
        row++;

        // Move elements of the last column from the remaining columns
        for (let i = row; i < m; i++) {
            curr = matrix[i][n - 1];
            matrix[i][n - 1] = prev;
            prev = curr;
        }
        n--;

        // Move elements of the last row from the remaining rows
        if (row < m) {
            for (let i = n - 1; i >= col; i--) {
                curr = matrix[m - 1][i];
                matrix[m - 1][i] = prev;
                prev = curr;
            }
        }
        m--;

        // Move elements of the first column from the remaining rows
        if (col < n) {
            for (let i = m - 1; i >= row; i--) {
                curr = matrix[i][col];
                matrix[i][col] = prev;
                prev = curr;
            }
        }
        col++;
    }
}

// Function to print the matrix
function printMatrix(matrix) {
    for (let i = 0; i < matrix.length; i++) {
        console.log(matrix[i].join(' '));
    }
}

// Main function to test the rotation
function main() {
    let matrix = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]
    ];

    rotateMatrix(matrix);
    printMatrix(matrix);
}

// Run the main function
main();
PHP
<?php
// PHP program to rotate a matrix
$R = 4;
$C = 4;

// A function to rotate a matrix 
// mat[][] of size R x C. Initially,
// m = R and n = C
function rotatematrix($m, $n, $mat)
{
    global $R, $C;
    $row = 0;
    $col = 0;
    $prev = 0;
    $curr = 0;

    /*
    row - Starting row index
    m - ending row index
    col - starting column index
    n - ending column index
    i - iterator
    */
    while ($row < $m && $col < $n)
    {

        if ($row + 1 == $m || 
            $col + 1 == $n)
            break;

        // Store the first element 
        // of next row, this element 
        // will replace first element 
        // of current row
        $prev = $mat[$row + 1][$col];

        /* Move elements of first row 
           from the remaining rows */
        for ($i = $col; $i < $n; $i++)
        {
            $curr = $mat[$row][$i];
            $mat[$row][$i] = $prev;
            $prev = $curr;
        }
        $row++;

        /* Move elements of last column
           from the remaining columns */
        for ($i = $row; $i < $m; $i++)
        {
            $curr = $mat[$i][$n - 1];
            $mat[$i][$n - 1] = $prev;
            $prev = $curr;
        }
        $n--;

        /* Move elements of last row
           from the remaining rows */
        if ($row < $m)
        {
            for ($i = $n - 1;
                 $i >= $col; $i--)
            {
                $curr = $mat[$m - 1][$i];
                $mat[$m - 1][$i] = $prev;
                $prev = $curr;
            }
        }
        $m--;

        /* Move elements of first column
           from the remaining rows */
        if ($col < $n)
        {
            for ($i = $m - 1; 
                 $i >= $row; $i--)
            {
                $curr = $mat[$i][$col];
                $mat[$i][$col] = $prev;
                $prev = $curr;
            }
        }
        $col++;
    }

    // Print rotated matrix
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
        echo $mat[$i][$j] . " ";
        echo "\n";
    }
}

// Driver code

// Test Case 1
$a = array(array(1, 2, 3, 4),
           array(5, 6, 7, 8),
           array(9, 10, 11, 12),
           array(13, 14, 15, 16));

// Test Case 2
/* int $a = array(array(1, 2, 3),
                  array(4, 5, 6),
                  array(7, 8, 9));
*/ rotatematrix($R, $C, $a);
    return 0;
    
?>

Output
5 1 2 3 
9 10 6 4 
13 11 7 8 
14 15 16 12 

Complexity Analysis:

  • Time Complexity: O(m*n) where m is the number of rows & n is the number of columns.
  • Auxiliary Space: O(1). 

Rotate Matrix Elements using Transpose and Reverse – O(n2) time and O(1) auxiliary space

This approach simplifies the problem by using two well-known matrix operations: transpose and reverse. The process can be broken down into two main steps:

  1. Transpose the Matrix:
    • The transpose of a matrix is obtained by swapping the rows with columns. In other words, for each element at position (i, j), we swap it with the element at position (j, i).
    • This operation essentially mirrors the matrix along its main diagonal.
  2. Reverse Columns:
    • After transposing the matrix, we reverse the order of elements in each column. This operation effectively rotates the elements to their new positions in a clockwise manner.


Code Implementation:

C++
#include <iostream>
#include <vector>

using namespace std;

// Function to rotate the matrix in a clockwise direction
void rotateMatrix(vector<vector<int> >& matrix)
{
    int n = matrix.size();

    // Transpose the matrix
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            swap(matrix[i][j], matrix[j][i]);
        }
    }

    // Reverse the columns
    for (int i = 0; i < n; i++) {
        for (int j = 0, k = n - 1; j < k; j++, k--) {
            swap(matrix[j][i], matrix[k][i]);
        }
    }
}

// Function to print the matrix
void printMatrix(vector<vector<int> >& matrix)
{
    for (int i = 0; i < matrix.size(); i++) {
        for (int j = 0; j < matrix[i].size(); j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
}

int main()
{
    vector<vector<int> > matrix
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    cout << "Original matrix:" << endl;
    printMatrix(matrix);
    rotateMatrix(matrix);
    cout << "Rotated matrix:" << endl;
    printMatrix(matrix);
    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class Main {

    // Function to rotate the matrix in a clockwise
    // direction
    public static void
    rotateMatrix(List<List<Integer> > matrix)
    {
        int n = matrix.size();

        // Transpose the matrix
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                int temp = matrix.get(i).get(j);
                matrix.get(i).set(j, matrix.get(j).get(i));
                matrix.get(j).set(i, temp);
            }
        }

        // Reverse the columns
        for (int i = 0; i < n; i++) {
            for (int j = 0, k = n - 1; j < k; j++, k--) {
                int temp = matrix.get(j).get(i);
                matrix.get(j).set(i, matrix.get(k).get(i));
                matrix.get(k).set(i, temp);
            }
        }
    }

    // Function to print the matrix
    public static void
    printMatrix(List<List<Integer> > matrix)
    {
        for (int i = 0; i < matrix.size(); i++) {
            for (int j = 0; j < matrix.get(i).size(); j++) {
                System.out.print(matrix.get(i).get(j)
                                 + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args)
    {
        List<List<Integer> > matrix = new ArrayList<>();
        matrix.add(new ArrayList<Integer>() {
            {
                add(1);
                add(2);
                add(3);
            }
        });
        matrix.add(new ArrayList<Integer>() {
            {
                add(4);
                add(5);
                add(6);
            }
        });
        matrix.add(new ArrayList<Integer>() {
            {
                add(7);
                add(8);
                add(9);
            }
        });
        System.out.println("Original matrix:");
        printMatrix(matrix);
        rotateMatrix(matrix);
        System.out.println("Rotated matrix:");
        printMatrix(matrix);
    }
}
Python
def rotate_matrix(matrix):
    n = len(matrix)
    
    # Transpose the matrix
    for i in range(n):
        for j in range(i, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    
    # Reverse the columns
    for i in range(n):
        for j, k in zip(range(n//2), range(n-1, n//2-1, -1)):
            matrix[j][i], matrix[k][i] = matrix[k][i], matrix[j][i]

def print_matrix(matrix):
    for row in matrix:
        print(' '.join(str(elem) for elem in row))

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Original matrix:")
print_matrix(matrix)
rotate_matrix(matrix)
print("Rotated matrix:")
print_matrix(matrix)
C#
using System;
using System.Collections.Generic;

class Program {
// Function to rotate the matrix in a clockwise
// direction
public static void RotateMatrix(List<List<int>> matrix) {
int n = matrix.Count;
     // Transpose the matrix
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }

    // Reverse the columns
    for (int i = 0; i < n; i++) {
        for (int j = 0, k = n - 1; j < k; j++, k--) {
            int temp = matrix[j][i];
            matrix[j][i] = matrix[k][i];
            matrix[k][i] = temp;
        }
    }
}

// Function to print the matrix
public static void PrintMatrix(List<List<int>> matrix) {
    for (int i = 0; i < matrix.Count; i++) {
        for (int j = 0; j < matrix[i].Count; j++) {
            Console.Write(matrix[i][j] + " ");
        }
        Console.WriteLine();
    }
}

static void Main(string[] args) {
    List<List<int>> matrix = new List<List<int>>();
    matrix.Add(new List<int>() { 1, 2, 3 });
    matrix.Add(new List<int>() { 4, 5, 6 });
    matrix.Add(new List<int>() { 7, 8, 9 });

    Console.WriteLine("Original matrix:");
    PrintMatrix(matrix);
    RotateMatrix(matrix);
    Console.WriteLine("Rotated matrix:");
    PrintMatrix(matrix);
}
}
JavaScript
// Function to rotate the matrix in a clockwise direction
function rotateMatrix(matrix) {
    const n = matrix.length;

    // Transpose the matrix
    for (let i = 0; i < n; i++) {
        for (let j = i; j < n; j++) {
            let temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }

    // Reverse the columns
    for (let i = 0; i < n; i++) {
        for (let j = 0, k = n - 1; j < k; j++, k--) {
            let temp = matrix[j][i];
            matrix[j][i] = matrix[k][i];
            matrix[k][i] = temp;
        }
    }
}

// Function to print the matrix
function printMatrix(matrix) {
    for (let i = 0; i < matrix.length; i++) {
        console.log(matrix[i].join(' '));
    }
}

// Main function to test the rotation
function main() {
    const matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];
    console.log("Original matrix:");
    printMatrix(matrix);
    rotateMatrix(matrix);
    console.log("Rotated matrix:");
    printMatrix(matrix);
}

// Run the main function
main();

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

Time Complexity: O(n2)
Auxiliary Space: O(1)

Related Article:



Previous Article
Next Article

Similar Reads

Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5 22 7 12 9 2 23 18 13
10 min read
Rotate each ring of matrix anticlockwise by K elements
Given a matrix of order M*N and a value K, the task is to rotate each ring of the matrix anticlockwise by K elements. If in any ring elements are less than and equal K then don't rotate it. Examples: Input : k = 3 mat[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output: 4 8 12 16 3 10 6 15 2 11 7 14 1 5 9 13 Input : k = 2
14 min read
Javascript Program to Rotate Matrix Elements
Given a matrix, clockwise rotate elements in it. Examples: Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 For 4*4 matrix Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. The idea is to use loops similar to the program f
5 min read
Rotate a Matrix by 180 degree
Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space. Examples : Input : 1 2 3 4 5 6 7 8 9 Output : 9 8 7 6 5 4 3 2 1 Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 Method: 1 (Only prints rotated matrix) The solution of this problem is that t
15+ min read
Javascript Program for Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
2 min read
Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
9 min read
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Given a square matrix, turn it by 90 degrees in a clockwise direction without using any extra space. Examples: Input: 1 2 3 4 5 6 7 8 9 Output: 7 4 1 8 5 2 9 6 3 Input: 1 2 3 4 Output: 3 1 4 2 Method 1 Approach: The approach is similar to Inplace rotate square matrix by 90 degrees | Set 1. The only thing that is different is to print the elements o
15+ min read
Rotate matrix by 45 degrees
Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix. Examples: Input: N = 6, mat[][] = {{3, 4, 5, 1, 5, 9, 5}, {6, 9, 8, 7, 2, 5, 2}, {1, 5, 9, 7, 5, 3, 2}, {4, 7, 8, 9, 3, 5, 2}, {4, 5, 2, 9, 5, 6, 2}, {4, 5, 7, 2, 9, 8, 3}}Output: 3 6 4 1 9 5 4 5 8 1 4 7 9 7 54 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5
15+ min read
Rotate-matrix module in Python
The rotate-matrix is an interesting new python module, which allows conversion of a matrix(2-D array) into either clockwise rotation or anti-clockwise rotation. It at present consists of only two methods. You can loop through these methods for 'n' number of rotations. Installation This module doesn't come in-built with python but can be installed u
1 min read
Javascript Program for Rotate a Matrix by 180 degree
Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space.  Examples :  Input : 1 2 3 4 5 6 7 8 9 Output : 9 8 7 6 5 4 3 2 1 Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 Method: 1 (Only prints rotated matrix) The solution of this problem is that
6 min read
Javascript Program to Inplace rotate square matrix by 90 degrees | Set 1
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.Examples : Input: Matrix: 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7 The given matrix is rotated by 90 degree in anti-clockwise direction. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 The given matr
5 min read
Inplace rotate square matrix by 90 degrees | Set 1
Given a square matrix, turn it by 90 degrees in an anti-clockwise direction without using any extra space Examples: Input:Matrix: 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7 Input:Matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 Recommended PracticeRotate a 2D array without using extra spaceTry It!Note:
15+ min read
Rotate a matrix by 90 degree without using any extra space | Set 2
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space. Examples: Input: 1 2 3 4 5 6 7 8 9Output: 3 6 9 2 5 8 1 4 7 Rotated the input matrix by90 degrees in anti-clockwise direction.Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13Rotated the input matrix by9
15+ min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix
Given a matrix arr[][] of dimensions N * M, the task is to generate a matrix such that any cell (r, c) stores the sum of adjacent elements present horizontally, vertically, and diagonally in the given matrix. Examples: Input: arr[][] = {{1, 3}, {2, 4}}Output: {{9, 7}, {8, 6}}Explanation: Matrix is constructed by the following operations: For cell (
9 min read
Print Matrix after multiplying Matrix elements N times
Given a square matrix mat[][] and an integer N, the task is to print the matrix after multiplying the matrix N times. Examples: Input: mat[][] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 9}}, N = 2Output:25 31 4045 57 7481 103 134 Input: mat[][] = {{1, 2}, {3, 4}}, N = 3Output:37 5481 118 Approach: The idea is to use the Matrix Multiplication identity matrix.
9 min read
Convert given Matrix into a Symmetric Matrix by replacing elements at (i, j) and (j, i) with their mean
Given an integer N and a N x N matrix, the task is to convert the given matrix into a symmetric matrix by replacing (i, j)th and (j, i)th element with their arithmetic mean. Examples: Input: arr[] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output: 1 3 53 5 75 7 9Explanation: The diagonal elements are same. The element at index (0, 1) = 2 and (1, 0) = 4 is
6 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n).Right (Or clockwise) rotate the given string by d elements (where d &lt;= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places.Examples: Input: list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6, m = 2, n = 5, k = 2 Output: 1-&gt;4-&gt;5-&gt;2-&gt;3-&gt;6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
13 min read
Python | Ways to rotate a list
The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is quite essential in a programmer's life to achieve various tasks. Let's discuss different ways we can rotate a list in Python. Method 1: Rotate a list usin
8 min read
Javascript Program for Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d Asked in Amazon To rotate the Doubly linked list, we
4 min read
Left rotate digits of node values of all levels of a Binary Tree in increasing order
Given a Binary Tree, the task is to modify the Tree by left rotating every node any number of times such that every level consists of node values in increasing order from left to right. If it is not possible to arrange node values of any level in increasing order, then print "-1". Examples: Input: 341 / \ 241 123 / \ \ 324 235 161Output: 341 / \ 12
14 min read
Javascript Program to Rotate digits of a given number by K
Given two integers N and K, the task is to rotate the digits of N by K. If K is a positive integer, left rotate its digits. Otherwise, right rotate its digits. Examples: Input: N = 12345, K = 2Output: 34512 Explanation: Left rotating N(= 12345) by K(= 2) modifies N to 34512. Therefore, the required output is 34512 Input: N = 12345, K = -3Output: 34
2 min read
Javascript Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Javascript Program to Rotate Linked List block wise
Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left. Examples:  Input: 1->2->3->4->5->6->7->8->9->NULL, k = 3 d = 1 Output: 3->1->2->6->4->5->9->7->8->NULL Explanation: Here blocks of size 3 are rotated towards righ
4 min read
Right rotate given Array K times using Pointers
Given an array arr[] of size N and an integer K, the task is to right rotate the array K times. Examples: Input: arr[] = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5Explanation: After 1st rotation - {9, 1, 3, 5, 7}After 2nd rotation - {7, 9, 1, 3, 5} Input: {1, 2, 3, 4, 5, 6}, K = 2Output: 5 6 1 2 3 4 Approach: The naive approach and approach based on r
6 min read
Left rotate Linked List by X in groups of Y nodes
Given a singly linked list and two integers X and Y, the task is to left rotate the linked list by X in groups of Y nodes. Examples: Input: 10 -&gt; 20 -&gt; 30 -&gt; 40 -&gt; 50 -&gt; 60 -&gt; 70 -&gt; 80 -&gt; 90 -&gt; 100, X = 2, Y = 4Output: 30 -&gt; 40 -&gt; 10 -&gt; 20 -&gt; 70 -&gt; 80 -&gt; 50 -&gt; 60 -&gt; 90 -&gt; 100Explanation: First g
10 min read
Rotate bits of a number
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put back at left end. Recommended PracticeRotate BitsTry
11 min read
Javascript Program for Program to cyclically rotate an array by one
Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Following are steps. 1) Store last element in a variable say x. 2) Shift all elements one position ahead. 3) Replace first element o
2 min read
Article Tags :
Practice Tags :