Taro Logo

Rotate Image

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+34
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.2K views
Topics:
Arrays

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

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

Example 2:

Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Constraints:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Is the input matrix guaranteed to be a square ($n \times n$) matrix, and what is the minimum and maximum possible value of $n$?
  2. What data type are the elements inside the matrix (e.g., 32-bit integers, floats), and are negative numbers or zeros allowed?
  3. Since the problem states we must do this in-place, should the function return anything (like a reference to the modified matrix), or is a `void` return type expected?
  4. Can I assume the input matrix is well-formed, or do I need to handle edge cases like null, empty matrices, or a $1 \times 1$ matrix?
  5. Should the rotation be strictly 90 degrees clockwise, or do I need to account for counter-clockwise rotation or arbitrary multiples of 90 degrees?

Brute Force Solution

Approach

Imagine you have a square picture made of a grid of tiny colored squares that you need to turn sideways by a quarter turn. The brute force strategy involves grabbing a brand new, empty canvas and systematically copying every single piece of the picture over to its new rotated home one by one.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first row of the original picture from top to bottom.
  2. Take that entire top row and prepare to place it so that it becomes the rightmost column of the new canvas.
  3. Carefully pick up each individual piece from that row, keeping them in their exact relative order.
  4. Place those pieces into the new canvas starting from the top down along that rightmost column.
  5. Move on to the next row down in the original picture and repeat the process.
  6. Place these pieces into the column immediately to the left of the previous one on the new canvas.
  7. Continue this exact same process for every remaining row in the original picture, shifting one column further to the left each time.
  8. Once every single piece has been copied over to the new canvas, the rotation is complete.

Code Implementation

def rotate(matrix):
    matrix_dimension = len(matrix)
    
    # Initialize a new canvas with zeros to safely build the rotated version without data corruption
    rotated_canvas = [[0 for column_index in range(matrix_dimension)] for row_index in range(matrix_dimension)]
    
    for original_row_index in range(matrix_dimension):
        for original_column_index in range(matrix_dimension):
            
            # Calculate the new column position from the right so rows map correctly to columns
            target_column_index = matrix_dimension - 1 - original_row_index
            target_row_index = original_column_index
            
            rotated_canvas[target_row_index][target_column_index] = matrix[original_row_index][original_column_index]
    
    # Copy every element back into the original matrix reference to satisfy in-place requirements
    for row_index in range(matrix_dimension):
        for column_index in range(matrix_dimension):
            matrix[row_index][column_index] = rotated_canvas[row_index][column_index]

Big(O) Analysis

Time Complexity
O(n²) – To rotate the image, the algorithm iterates through every single cell in the n by n grid to copy it to its new location on a separate canvas. There is an outer loop traversing each of the n rows, and an inner loop visiting each of the n elements within that row. This nested traversal results in exactly n times n, or n squared, individual copy operations. Approximating this work leads to n² total operations, which simplifies to a Big O time complexity of O(n²).
Space Complexity
O(N^2) – The provided plain English strategy explicitly requires grabbing a brand new, empty canvas to systematically copy every single piece of the picture over to its new rotated home. Because the input is an N by N square grid containing N squared total elements, this brand new canvas requires allocating an auxiliary two-dimensional data structure of size N by N to store the intermediate results. As the input dimensions grow, the extra memory needed to hold this separate canvas scales proportionally with the total number of elements. Therefore, the auxiliary space complexity simplifies to Big O of N squared.

Optimal Solution

Approach

Instead of trying to move every single piece to its final destination all at once, which gets very messy, we can achieve the same rotation by performing two simple physical flips. This clever shortcut lets us rearrange everything neatly in place without needing extra space.

Here's how the algorithm would work step-by-step:

  1. First, take the entire picture and flip it upside down so the top edge becomes the bottom edge and vice versa.
  2. Next, fold the picture diagonally from the top-left corner to the bottom-right corner, and swap every piece on one side of this fold with its matching partner on the other side.
  3. By doing just these two straightforward physical adjustments, the picture is now rotated perfectly by ninety degrees clockwise.

Code Implementation

def rotate(matrix):
    matrix_dimension = len(matrix)

    # Flipping upside down prepares the rows to become columns in their correct inverted order.
    for row_index in range(matrix_dimension // 2):
        for column_index in range(matrix_dimension):
            matrix[row_index][column_index], matrix[matrix_dimension - 1 - row_index][column_index] = matrix[matrix_dimension - 1 - row_index][column_index], matrix[row_index][column_index]

    # Transposing across the diagonal completes the 90-degree clockwise rotation efficiently in place.
    for row_index in range(matrix_dimension):
        for column_index in range(row_index + 1, matrix_dimension):
            matrix[row_index][column_index], matrix[column_index][row_index] = matrix[column_index][row_index], matrix[row_index][column_index]

Big(O) Analysis

Time Complexity
O(n²) – The time complexity is driven by two sequential phases operating on an n by n matrix. The first phase reverses the rows by iterating through half of the n rows and swapping elements, taking approximately n * n/2 operations. The second phase performs a diagonal transpose by iterating through the upper triangle of the matrix and swapping elements across the main diagonal, which also takes approximately n * n/2 operations. Combining these two steps results in roughly n² total operations, which simplifies to the final Big O time complexity of O(n²).
Space Complexity
O(1) – The algorithm performs all operations directly on the input matrix by modifying elements in place through swapping. It only uses a few primitive variables as temporary pointers for the swap operations, meaning no extra data structures scale with the input size N. Therefore, the auxiliary space complexity remains constant regardless of how large the image matrix grows.

Edge Cases

Empty or null matrix input
How to Handle:
Check for null or empty references at the start to immediately return without throwing runtime exceptions.
Minimum sized 1x1 matrix
How to Handle:
The algorithm skips rotation loops since layers are non-existent, leaving the single element correctly untouched.
2x2 matrix minimum multi-element case
How to Handle:
The outer and inner loop bounds correctly process the single four-element quadrant swap without out of bounds errors.
Large scale matrices up to maximum constraints
How to Handle:
The in-place O(1) extra space transpose and reverse approach avoids memory limit issues while running in optimal O(N squared) time.
Matrix containing all identical values
How to Handle:
Swapping identical values produces no visible change but executes the index math safely without data corruption.
Matrix with extreme values like negatives and zeros
How to Handle:
Since the approach relies purely on index swapping rather than arithmetic operations, any integer value is handled uniformly.
Odd versus even dimensions of n by n matrix
How to Handle:
Adjusting the layer boundaries for outer and inner loops correctly handles the exact center element in odd dimensions.
Memory constraint limits with in-place requirement
How to Handle:
Mutating the original 2D array directly satisfies the strict O(1) auxiliary space requirement without allocating auxiliary grids.
0/75 completed