Skip to content

Rotate Image

Medium

The problem

matrix is an n × n grid of numbers. Rotate it 90 degrees clockwise by changing the grid itself (do not make a second grid). The function returns nothing.

  • Example 1
    Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    Output: matrix becomes [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

    The first column read from the bottom up (7, 4, 1) becomes the first row.

  • Example 2
    Input: matrix = [[1, 2], [3, 4]]
    Output: matrix becomes [[3, 1], [4, 2]]
Limits
  • 1 ≤ n ≤ 20
  • -1,000 ≤ matrix[i][j] ≤ 1,000
  • Edit the matrix in place

Write it in Go. Try for about 20 minutes on paper first, then open one hint at a time.

Try it here

Write Go. Common packages like fmt and sort are imported for you. Keep the function name and inputs the same.

Hints, one at a time

Nudge

A 90° rotation is two simpler moves combined.

The idea

Transpose the matrix (swap [i][j] with [j][i]), then reverse each row. Or rotate four cells at a time layer by layer.

Target: O(n²) time, O(1) space

Go function shape
func rotate(matrix [][]int)
Reference solution

Tested with go test. Try it yourself first, then compare.

// Rotate: rotate an n×n matrix 90° clockwise in place = transpose, then reverse every row.
func Rotate(m [][]int) {
	n := len(m)
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			m[i][j], m[j][i] = m[j][i], m[i][j]
		}
	}
	for _, row := range m {
		for l, r := 0, n-1; l < r; l, r = l+1, r-1 {
			row[l], row[r] = row[r], row[l]
		}
	}
}