AlgoTales · Roadmap

Rotation

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Rotating a grid by a quarter turn moves every cell to a new place, and the whole thing can be done inside the same grid without making a copy. It is the logic behind turning pictures, game boards and tables to a new orientation.

Practical use cases

  • Web app: Photo opening sideways after upload. A user uploads a phone photo, and it appears turned on its side. The page reads the orientation note and rotates the pixel grid a quarter turn. Doing it in place matters when the photo has millions of pixels and the server has little spare memory.
  • Web app: Rotating a board in a browser game. A Tetris-style or puzzle game rotates a falling piece, which is a small grid, when the player taps rotate. The code turns the grid by a quarter turn instantly, so the game feels responsive on a phone. No second board is created, so even a low-end phone stays smooth.
  • System: Maps, sprites and scanned documents. Map tiles, game sprites and scanned documents are rotated to match the screen or page. Print software turns a landscape page to portrait the same way, moving each position to its new corner. Doing it in place keeps memory use low, which matters when a server rotates hundreds of uploaded scans per minute.

The story: The Tilted Notice Board

The school notice board had nine class photos in a 3 × 3 grid. The principal said, "Mount the board sideways in the new hall. Turn it a quarter turn clockwise." Photo 1, which sat top-left, now had to go top-right. Photo 7, bottom-left, had to become top-left.

The caretaker, Bhola Kaka, wanted to take all nine photos down, lay them on a table and re-hang them on a second board. Mira said, "No spare board! Do it on the same board."

She noticed something lovely. The four corner photos just pass the baton around the corners: top-left to top-right to bottom-right to bottom-left and back. The four edge photos did the same dance, in their own little circle. The centre photo stayed put.

So Mira lifted one photo into her hand, moved three others one step along the circle, and placed hers in the last empty spot. Two such cycles and the whole board was rotated. That is in-place matrix rotation: work layer by layer, swapping four cells at a time.

How to spot this problem, and where you need it

You must turn a square or rectangular grid by 90 degrees, and creating a second grid wastes memory or you cannot figure out where each cell goes.

Signs you need it

  • The problem says rotate the image or matrix by 90 degrees, clockwise or anti-clockwise, in place.
  • Users complain that uploaded photos, scans or PDF pages show sideways or upside down.
  • You are writing a game in which pieces or boards turn on a button press.

Where to use it in a project

  • Image upload pipelines that fix orientation before showing thumbnails or saving to storage.
  • Tile-based games and board editors where a selected piece or map must turn without redrawing everything.

The solution

A quarter turn clockwise equals two easy moves: first transpose the grid, swapping each cell with the one mirrored across the main diagonal; then reverse every row. For anti-clockwise, reverse the rows first or reverse each column afterwards. Both moves swap cells in place, so no second grid is needed.

Payoff: Before: a second full-size copy of a large image. After: the same grid turned in place with just two simple passes.

Explain it like I am 8

Put a square sheet of stickers on the table and turn the sheet a quarter turn. Every sticker moves to a new place, but the sticker in the exact middle stays. If you cannot lift the sheet, you move four stickers at once in a circle.

How it works, step by step

  1. Work from the outer layer to the inner layers of the square.
  2. For each position i along the top edge of the layer, find the four cells that rotate together: top, right, bottom and left.
  3. Save the top cell in a temporary variable.
  4. Move left to top, bottom to left, right to bottom, then temp to right.
  5. Repeat for every i in the layer (not the last one, it is covered by its own cycle), then step inward to the next layer.

The code in four languages

PHP

<?php
// Rotate an n x n matrix 90 degrees clockwise, in place, layer by layer
function rotate(array $m): array {
    $n = count($m);
    for ($l = 0; $l < intdiv($n, 2); $l++) {          // each ring
        for ($i = $l; $i < $n - 1 - $l; $i++) {       // each cycle in the ring
            $top = $m[$l][$i];                         // save top
            $m[$l][$i] = $m[$n - 1 - $i][$l];          // left -> top
            $m[$n - 1 - $i][$l] = $m[$n - 1 - $l][$n - 1 - $i];   // bottom -> left
            $m[$n - 1 - $l][$n - 1 - $i] = $m[$i][$n - 1 - $l];   // right -> bottom
            $m[$i][$n - 1 - $l] = $top;                // saved top -> right
        }
    }
    return $m;
}

$board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
foreach (rotate($board) as $row) {
    echo implode(' ', $row) . PHP_EOL;
}
// 7 4 1
// 8 5 2
// 9 6 3

JavaScript

// Rotate an n x n matrix 90 degrees clockwise, in place, layer by layer
function rotate(m) {
  const n = m.length;
  for (let l = 0; l < Math.floor(n / 2); l++) {       // each ring
    for (let i = l; i < n - 1 - l; i++) {             // each cycle in the ring
      const top = m[l][i];                            // save top
      m[l][i] = m[n - 1 - i][l];                      // left -> top
      m[n - 1 - i][l] = m[n - 1 - l][n - 1 - i];      // bottom -> left
      m[n - 1 - l][n - 1 - i] = m[i][n - 1 - l];      // right -> bottom
      m[i][n - 1 - l] = top;                          // saved top -> right
    }
  }
  return m;
}

const board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
for (const row of rotate(board)) {
  console.log(row.join(' '));
}
// 7 4 1
// 8 5 2
// 9 6 3

Java

public class Main {
    // Rotate an n x n matrix 90 degrees clockwise, in place, layer by layer
    static int[][] rotate(int[][] m) {
        int n = m.length;
        for (int l = 0; l < n / 2; l++) {                      // each ring
            for (int i = l; i < n - 1 - l; i++) {              // each cycle in the ring
                int top = m[l][i];                             // save top
                m[l][i] = m[n - 1 - i][l];                     // left -> top
                m[n - 1 - i][l] = m[n - 1 - l][n - 1 - i];     // bottom -> left
                m[n - 1 - l][n - 1 - i] = m[i][n - 1 - l];     // right -> bottom
                m[i][n - 1 - l] = top;                         // saved top -> right
            }
        }
        return m;
    }

    public static void main(String[] args) {
        int[][] board = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        for (int[] row : rotate(board)) {
            System.out.println(row[0] + " " + row[1] + " " + row[2]);
        }
        // 7 4 1
        // 8 5 2
        // 9 6 3
    }
}

Go

package main

import "fmt"

// rotate turns an n x n matrix 90 degrees clockwise, in place, layer by layer.
func rotate(m [][]int) [][]int {
	n := len(m)
	for l := 0; l < n/2; l++ { // each ring
		for i := l; i < n-1-l; i++ { // each cycle in the ring
			top := m[l][i]                // save top
			m[l][i] = m[n-1-i][l]         // left -> top
			m[n-1-i][l] = m[n-1-l][n-1-i] // bottom -> left
			m[n-1-l][n-1-i] = m[i][n-1-l] // right -> bottom
			m[i][n-1-l] = top             // saved top -> right
		}
	}
	return m
}

func main() {
	board := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
	for _, row := range rotate(board) {
		fmt.Println(row[0], row[1], row[2])
	}
	// 7 4 1
	// 8 5 2
	// 9 6 3
}

Time: O(n²) · Extra space: O(1). Every cell is moved once, and only one temporary variable is used. n is the side length, so n² is the number of cells.

Watch out for

  • Looping the inner index all the way to n - 1 rather than n - 1 - l. That rotates the corner twice.
  • Overwriting a cell before saving it. Always keep the first value in a temp variable.
  • Mixing clockwise and anti-clockwise. For clockwise, the left photo goes to the top.

Quick check

  1. In a 3 × 3 board, which photo never moves during rotation?
    • The top-left
    • The centre
    • The bottom-right
  2. How many cells move in each cycle?
    • Two
    • Three
    • Four
  3. Why do we need a temporary variable?
    • To save the first cell before overwriting it
    • To count the cycles
    • To store the size