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;
}
}
};
Difficulty
and has an acceptance rate of about 81% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Math
- Matrix
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 1886: Determine Whether Matrix Can Be Obtained By Rotation
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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