Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Rotate Image | Leetcode 48 | Explained with Images
    Data Structures & Algorithms

    Rotate Image | Leetcode 48 | Explained with Images

    codeanddebugBy codeanddebug29 June 2025No Comments4 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question to rotate image on leetcode
    Share
    Facebook Twitter LinkedIn Pinterest Email

    LeetCode “Rotate Image” (#48) asks you to rotate an n × n square matrix 90° clockwise in-place (i.e., without returning a new matrix).

    Example
    Input matrix

    1 2 3
    4 5 6
    7 8 9

    Desired output (90° clockwise)

    7 4 1
    8 5 2
    9 6 3

    A real-world analogy is rotating a photo on your phone: each pixel’s new position depends on its current row/column.

    Here’s the [Problem Link] to begin with.

    Contents:
     [show]
    • Brute Force Solution (Extra Matrix)
      • Intuition & Approach
      • Code Implementation
      • Code Explanation
      • Dry Run (3 × 3)
      • Time & Space Complexity
      • Conclusion
    • Optimal Solution (Transpose + Reverse)
      • Intuition & Approach
      • Code Implementation
      • Code Explanation
      • Dry Run (3 × 3)
      • Time & Space Complexity
      • Conclusion
    • Final Thoughts

    Brute Force Solution (Extra Matrix)

    Intuition & Approach

    The simplest mental model is to copy every element into the place where it should appear after rotation:

    • Element (row =i, col =j) moves to (row =j, col = n − 1 − i).
    • Because every element’s target is unique, we can safely write into a separate result matrix and finally overwrite the original.

    This costs extra space but keeps the logic crystal clear.

    Code Implementation

    class Solution:
        def rotate(self, matrix: List[List[int]]) -> None:        
            # dimensions
            r = len(matrix)
            c = len(matrix[0])
    
            # create an empty r × c matrix
            result = [[0 for _ in range(c)] for _ in range(r)]
    
            # place each value in its rotated position
            for i in range(r):
                for j in range(c):
                    # new row  = old column
                    # new col  = (last row index) - old row
                    result[j][r - 1 - i] = matrix[i][j]
    
            # copy the rotated picture back to the input matrix
            matrix[:] = result

    Code Explanation

    1. Allocate result filled with zeros.
    2. Double loop walks every (i, j) in the original.
    3. Compute its new coordinates and write to result.
    4. Assign matrix[:] = result to replace contents while keeping the same reference (important for LeetCode’s “in-place” checker).

    Dry Run (3 × 3)

    Step(i, j)matrix[i][j]Writes to resultresult after write
    10,01(0,2)1··<br/>····<br/>···
    20,12(1,2)1··<br/>2··<br/>···
    ……………
    92,29(2,0)7 4 1<br/>8 5 2<br/>9 6 3

    Final copy writes the rotated picture back.

    Time & Space Complexity

    • Time: O(n²) – we visit each of the n² entries once.
    • Space: O(n²) extra – the auxiliary matrix.

    Conclusion

    The brute-force way is straightforward and great for understanding coordinate mapping, but it doubles memory usage—so we can do better!


    Optimal Solution (Transpose + Reverse)

    Intuition & Approach

    A 90° clockwise rotation can be decomposed into two well-known in-place operations:

    1. Transpose – swap matrix[i][j] with matrix[j][i] for all i < j.
      Rows become columns.
    2. Reverse each row – flips elements left ↔ right.
      Converts the transposed picture into a rotated one.

    Because both steps modify cells in-place and never require extra rows/cols, the total extra space is O(1).

    Code Implementation

    class Solution:
        def rotate(self, matrix: List[List[int]]) -> None:
            """
            Do not return anything, modify matrix in-place instead.
            """
            n = len(matrix)
    
            # 1️⃣ Transpose the matrix (swap across the main diagonal)
            for i in range(n - 1):
                for j in range(i + 1, n):
                    # swap upper-triangle with lower-triangle element
                    matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    
            # 2️⃣ Reverse every row to finish the 90° rotation
            for i in range(n):
                matrix[i].reverse()

    Code Explanation

    • Transpose loop:
      Only the upper triangle (j > i) is swapped to avoid undoing previous swaps.
    • Reverse loop:
      Python’s list.reverse() reverses each row in-place.

    Together they replicate the mathematical definition of rotation without touching extra memory.

    Dry Run (3 × 3)

    Start

    1 2 3
    4 5 6
    7 8 9

    After transpose

    1 4 7
    2 5 8
    3 6 9

    After row reversals

    7 4 1
    8 5 2
    9 6 3

    Matches the desired output 👌.

    Time & Space Complexity

    • Time: O(n²) – same double loop size.
    • Space: O(1) – only a few temporary variables for swapping.

    Conclusion

    By leveraging matrix properties (transpose + reverse), we hit optimal memory usage while maintaining clear, readable code. This is the go-to technique in interviews when asked to “rotate image in-place.”


    Final Thoughts

    • Start with the brute-force version to internalize coordinate transformations.
    • Then graduate to the elegant transpose-then-reverse pattern for production-ready, space-efficient solutions.
    • Remember: both run in O(n²) time—but optimal wins on memory.
    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    2D Array Medium
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleSet Matrix Zeroes | Leetcode 73 | Explained
    Next Article Spiral Matrix | Leetcode 54 | Explained in Python
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Search in Rotated Sorted Array | Leetcode 33 | Optimal Binary Search

    3 July 2025
    Data Structures & Algorithms

    Count occurrences of a number in a sorted array with duplicates | Optimal Binary Search

    3 July 2025
    Data Structures & Algorithms

    Find First and Last Position of Element in Sorted Array | Leetcode 34 | Optimal Binary Search

    2 July 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (93)
      • Beginner (44)
      • Expert (22)
      • Intermediate (27)
    • Uncategorised (1)
    Recent Posts

    Search in Rotated Sorted Array | Leetcode 33 | Optimal Binary Search

    3 July 2025

    Count occurrences of a number in a sorted array with duplicates | Optimal Binary Search

    3 July 2025

    Find First and Last Position of Element in Sorted Array | Leetcode 34 | Optimal Binary Search

    2 July 2025

    Ceil The Floor | Binary Search Implementation

    2 July 2025

    Search Insert Position | Leetcode 35 | Explained in Python

    2 July 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.