Rotate Image
Rotate Image
Section titled “Rotate Image”
Medium
Day 10 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Rotate an n x n 2D matrix 90 degrees clockwise in-place.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]] - Output:
[[7,4,1],[8,5,2],[9,6,3]]
Constraints:
n == matrix.length1 <= n <= 20
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Transpose matrix (swap matrix[i][j] with matrix[j][i]), then reverse each row.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Transpose + Reverse Rows
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD Start["Input Data"] --> Process["Process Element by Element"] Process --> Lookup{"Hash Map / Set Lookup"} Lookup -- "Match Found" --> Return["Return Indices / Result"] Lookup -- "No Match" --> Store["Store in Map / Set"] Store --> Process🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”function rotate(matrix) { const n = matrix.length; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; } } for (let i = 0; i < n; i++) matrix[i].reverse(); return matrix;}- Time Complexity:
O(n^2) - Space Complexity:
O(1) - Explanation: In-place transpose and row reverse.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function rotate(matrix) { const n = matrix.length; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; } } for (let i = 0; i < n; i++) matrix[i].reverse(); return matrix;}- Time Complexity:
O(n^2) - Space Complexity:
O(1) - Explanation: Transpose matrix diagonally, then flip rows horizontally.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”Rotate 90 deg clockwise = Transpose matrix + Reverse rows.
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Transpose then reverse each row.