Faaez Razeen

Rotate Image

  • 2 min read
  • LC-Medium
  • Math-and-geometry

3 years ago

Solution 1

TimeSpaceExplanation
O(n)O(1)where n is the size of the matrix
def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ l, r = 0, len(matrix) - 1 while l < r: t, b = l, r for i in range(r - l): top_left = matrix[t][l + i] matrix[t][l + i] = matrix[b - i][l] matrix[b - i][l] = matrix[b][r - i] matrix[b][r - i] = matrix[t + i][r] matrix[t + i][r] = top_left l += 1 r -= 1

Solution 2 (Transpose + Reverse)

def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ # Transpose n = len(matrix) for r in range(n): for c in range(r + 1, n): matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c] # Reverse for row in range(n): l, r = 0, n - 1 while l < r: matrix[row][l], matrix[row][r] = matrix[row][r], matrix[row][l] l += 1 r -= 1