1. Auxiliary Matrix Copy (Brute Force)
Intuition
Create an auxiliary matrix res of size n x n. For every row r from 0 to n-1 and column c from 0 to n-1, assign res[c][n - 1 - r] = matrix[r][c]. Finally, copy res back into matrix.
When to apply: Use to understand the mathematical rotation formula before optimizing to in-place.
Auxiliary Matrix Rotation Trace
2 of 2 questions left todayMatrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. Allocate empty 3x3 auxiliary grid res.
import java.util.*; public class Main { public static class Solution { public void rotate(int[][] matrix) { int n = matrix.length; int[][] res = new int[n][n]; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { res[c][n - 1 - r] = matrix[r][c]; } } for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { matrix[r][c] = res[r][c]; } } } } public static void main(String[] args) { Solution sol = new Solution(); int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; sol.rotate(matrix); System.out.println("Rotated matrix: " + Arrays.deepToString(matrix)); }}Time & Space Complexity
- Time complexity:
O(n^2)— Visiting all n x n cells takes O(n2) operations. - Space complexity:
O(n^2)— Requires an auxiliary n x n matrix.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.