DevPath

← All problems

Rotate Image 90 Degrees

Medium matrix

Description

Rotate the square matrix 90 degrees clockwise and return it.

Constraints

1 <= n <= 100

Examples

Input: matrix = [[1,2],[3,4]]

Output: [[3,1],[4,2]]

Hints (1)
  • Transpose then reverse each row.

Solutions

Transpose then reverse rows. · Time O(n^2) · Space O(1)

func rotate90(matrix [][]int) [][]int {
    n := len(matrix)
    a := make([][]int, n)
    for i := range matrix {
        a[i] = append([]int{}, matrix[i]...)
    }
    for i := 0; i < n; i++ {
        for j := i + 1; j < n; j++ {
            a[i][j], a[j][i] = a[j][i], a[i][j]
        }
    }
    for i := range a {
        for l, r := 0, n-1; l < r; l, r = l+1, r-1 {
            a[i][l], a[i][r] = a[i][r], a[i][l]
        }
    }
    return a
}

Create a free account to submit solutions, track progress and save problems.

Create account