Rotate a Matrix In Place
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in in-place matrix and array manipulation, understanding of spatial transformations, and consideration of space and time complexity constraints.
Part 1: Rotate Matrix 90 Degrees Clockwise In Place
Constraints
- 0 <= n <= 200
- matrix is square: matrix has n rows and each row has n columns
- -10^9 <= matrix[i][j] <= 10^9
Examples
Input: []
Expected Output: []
Explanation: Empty matrix stays empty.
Input: [[42]]
Expected Output: [[42]]
Explanation: A 1x1 matrix is unchanged after rotation.
Input: [[1,2],[3,4]]
Expected Output: [[3,1],[4,2]]
Explanation: The top row becomes the right column.
Input: [[1,2,3],[4,5,6],[7,8,9]]
Expected Output: [[7,4,1],[8,5,2],[9,6,3]]
Explanation: Standard 3x3 clockwise rotation.
Input: [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Expected Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Explanation: Works for larger square matrices too.
Hints
- Try breaking the rotation into two simpler in-place operations.
- After transposing a matrix, what row operation turns it into a clockwise rotation?