Leetcode 48: Rotate Image

grid47
grid47
Exploring patterns and algorithms
Nov 2, 2024 4 min read

A serene, slow-moving image rotating in space, shifting with soft, calming colors.
Solution to LeetCode 48: Rotate Image Problem

Given an n x n 2D matrix representing an image, rotate the image by 90 degrees clockwise. The rotation should be done in-place, meaning you cannot allocate another 2D matrix.
Problem
Approach
Steps
Complexity
Input: The input is a 2D matrix representing an image. The matrix is of size n x n, where n is between 1 and 20.
Example: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Constraints:
• 1 <= n <= 20
• Each element of the matrix is an integer between -1000 and 1000.
Output: Return the matrix after rotating it by 90 degrees clockwise.
Example: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Constraints:
• The result should be the rotated matrix, achieved in-place.
Goal: The goal is to rotate the matrix 90 degrees clockwise in-place without using extra space for another matrix.
Steps:
• 1. Reverse the rows of the matrix.
• 2. Transpose the matrix by swapping the elements along the diagonal.
Goal: The input matrix has a size of n x n, where n is between 1 and 20. All matrix elements are integers between -1000 and 1000.
Steps:
• The matrix size is between 1 and 20.
• Matrix elements are integers in the range [-1000, 1000].
Assumptions:
• The matrix will always be a square matrix with the same number of rows and columns.
Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Explanation: In this example, after reversing the rows and transposing, the final result is [[7, 4, 1], [8, 5, 2], [9, 6, 3]].

Input: [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]
Explanation: In this example, after rotating the matrix 90 degrees clockwise, the final result is [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus