Problem 48

Abstract / Summary

Given a square matrix, rotate its elements ninety degrees clockwise in place.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0048.cpp

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int size = matrix.size();
        int m    = size - 1;
        for (int x = 0; x < (size+1)/2; x++)
            for (int y = 0; y < size/2; y++)
            {
                int tmp = matrix[x][y];
                matrix[  x][  y] = matrix[m-y][  x];
                matrix[m-y][  x] = matrix[m-x][m-y];
                matrix[m-x][m-y] = matrix[  y][m-x];
                matrix[  y][m-x] = tmp;
            }
    }
};
16 lines | 517 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 81% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided rotate method implements an in-place 90-degree clockwise rotation of a square matrix represented as a vector<vector<int>>. The algorithm works by moving elements in groups of four, effectively rotating the outer layer first and then proceeding inward. All operations are performed directly on the input matrix, eliminating the need for auxiliary storage.

Key Steps

Determining matrix dimensions

int size = matrix.size();
int m    = size - 1;

The variable size holds the length of one side of the square matrix. The helper m represents the index of the last row or column, simplifying later calculations that reference the opposite side of the matrix.

Iterating over the upper-left quadrant

for (int x = 0; x < (size+1)/2; x++)
    for (int y = 0; y < size/2; y++)
    {
        // rotation logic
    }

Two nested loops traverse only the cells that belong to the upper-left quadrant of the matrix. The outer loop runs up to the middle row (rounded up for odd sizes), while the inner loop runs up to the middle column (rounded down). This selection guarantees that each group of four cells is visited exactly once.

Performing the four-way swap

int tmp = matrix[x][y];
matrix[  x][  y] = matrix[m-y][  x];
matrix[m-y][  x] = matrix[m-x][m-y];
matrix[m-x][m-y] = matrix[  y][m-x];
matrix[  y][m-x] = tmp;

A temporary variable stores the value at the current position (x, y). The subsequent assignments rotate the values from the left side to the top, from the bottom to the left, from the right to the bottom, and finally place the saved top value into the right side. The use of direct index arithmetic (m - y, m - x) maps each position to its counterpart after a 90-degree rotation.

Edge Cases Handled

When the matrix is empty (size == 0), the outer loop condition evaluates to false, and the function exits without performing any work. For a single-element matrix (size == 1), the inner loop range becomes zero, so no swaps occur, leaving the matrix unchanged as expected. The loop bounds also correctly handle both even and odd dimensions, ensuring that the central row or column in odd-sized matrices is not processed redundantly.

Performance Optimizations

The algorithm achieves in-place transformation, requiring only a single integer temporary variable regardless of matrix size. By limiting iteration to half the rows and half the columns, the number of processed elements is reduced to exactly one quarter of the total cells, which is the theoretical minimum for a four-way rotation. The use of simple arithmetic for index calculation avoids function calls or additional data structures, keeping the inner loop tight and cache-friendly. This design results in a fast execution path that scales linearly with the number of elements in the matrix.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a square puzzle board filled with colorful tiles. The goal is to turn the whole board to the right, just like how you might spin a plate on a table. To do this, the computer looks at the tiles in groups of four. It picks up one tile at a time and moves it to a new spot, then moves the next one into the empty hole, and keeps doing this until every corner and middle piece has traveled to its new home. It uses a temporary storage spot to hold one tile while it swaps the others around in a circle. By repeating this little dance, every single tile ends up in the perfect position to make the whole square look like it has been rotated.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.63 | σ = 1.28

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Java Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak Python
withaarzoo C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak Python
withaarzoo C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
63 links | 46 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode 48. Rotate Image (Solution Explained)'
Nick White 11 mins
LeetCode 48. Rotate Image (Solution Explained)
YouTube video 'Rotate Image - Leetcode 48 - Arrays & Strings (Python)'
Greg Hogg 6 mins
Rotate Image - Leetcode 48 - Arrays & Strings (Python)
YouTube video 'Rotate Image | Simplest Explanation | Detailed | Leetcode 48 | codestorywithMIK'
codestorywithMIK 10 mins
Rotate Image | Simplest Explanation | Detailed | Leetcode 48 | codestorywithMIK
YouTube video 'Rotate Image (Leetcode 48) | Full solution with examples visuals and animation | Study Algorithms'
Nikhil Lohia 15 mins
Rotate Image (Leetcode 48) | Full solution with examples visuals and animation | Study Algorithms
YouTube video 'Rotate Image | Leetcode 48 Solution in Hindi'
Pepcoding 12 mins
Rotate Image | Leetcode 48 Solution in Hindi
YouTube video 'Rotate Image | Live Coding with Explanation | Leetcode - 48'
Algorithms Made Easy 11 mins
Rotate Image | Live Coding with Explanation | Leetcode - 48
YouTube video 'LeetCode 48: Rotate Image | Rotate N*N Matrix | Rotate a Square - Interview Prep Ep 54'
Fisher Coder 34 mins
LeetCode 48: Rotate Image | Rotate N*N Matrix | Rotate a Square - Interview Prep Ep 54
YouTube video 'Rotate Image - LeetCode 48 - JavaScript'
AlgoJS 7 mins
Rotate Image - LeetCode 48 - JavaScript
YouTube video 'Rotate Image - LeetCode 48 - Java'
LeetCode University 25 mins
Rotate Image - LeetCode 48 - Java
YouTube video 'Rotate Image | LeetCode 48 | Theory + Python code'
Sai Anish Malla 11 mins
Rotate Image | LeetCode 48 | Theory + Python code
YouTube video 'Rotate Image || 2D Matrix || Array-25 || Placement Preparation Series || Leetcode 48 ||'
Bro Coders 8 mins
Rotate Image || 2D Matrix || Array-25 || Placement Preparation Series || Leetcode 48 ||
YouTube video 'Leetcode 48 Rotate Image | Coding Decoded SDE preparation Sheet'
Coding Decoded 4 mins
Leetcode 48 Rotate Image | Coding Decoded SDE preparation Sheet
YouTube video 'LeetCode 48 | Rotate Image | Solution Explained (Java + Whiteboard)'
Xavier Elon 12 mins
LeetCode 48 | Rotate Image | Solution Explained (Java + Whiteboard)
YouTube video 'Rotate Image | Leetcode 48 | Matrix | O(1) Space #dsa'
Learn With Chirag 9 mins
Rotate Image | Leetcode 48 | Matrix | O(1) Space #dsa
YouTube video 'LeetCode in C# | 48. Rotate Image'
Josh Ackland 10 mins
LeetCode in C# | 48. Rotate Image
YouTube video 'Daily Leetcode #882: Aug 30, 2022 - 48. Rotate Image'
Programming Live with Larry 13 mins
Daily Leetcode #882: Aug 30, 2022 - 48. Rotate Image
YouTube video '48. Rotate Image | Leetcode Daily - Python'
Leetcode Daily 7 mins
48. Rotate Image | Leetcode Daily - Python
YouTube video 'Leetcode 48: Rotate Image in Telugu | In-Place Matrix Rotation | Python DSA | SRKCodes'
Srk Codes 10 mins
Leetcode 48: Rotate Image in Telugu | In-Place Matrix Rotation | Python DSA | SRKCodes
YouTube video 'šŸ„‡Leetcode 48 Rotate Image | Medium | Python | #amazon, #google and #microsoftšŸ”„ #leetcode #coding'
AccelerateAI Careers 15 mins
šŸ„‡Leetcode 48 Rotate Image | Medium | Python | #amazon, #google and #microsoftšŸ”„ #leetcode #coding
YouTube video 'Rotate Image - Leetcode 48 | 3 Approaches Explained'
Code With K5KC 14 mins
Rotate Image - Leetcode 48 | 3 Approaches Explained
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality