Coding questions · Apple
Rotate a Matrix In Place
This question evaluates proficiency in in-place matrix and array manipulation, spatial data transformation, and reasoning about time and space complexity.
Given an n x n matrix of integers, rotate the matrix 90 degrees clockwise.
Implement the function in Python. You may use a straightforward approach with loops, but the preferred solution should rotate the matrix in place without allocating another n x n matrix.
Example:
Input:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output:
[
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
Discuss the time and space complexity of your approach.
Rotate a Matrix In Place
Given an n x n matrix of integers, rotate the matrix 90 degrees clockwise.
Return the rotated matrix. The preferred solution modifies the matrix in place without allocating another n x n matrix, although straightforward loop-based reasoning is acceptable.
For example, rotating
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
produces
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]].
Constraints
- 0 <= n <= 200
- -10^9 <= matrix[i][j] <= 10^9
- The input matrix is square (has exactly n rows and n columns)
Hints
- Track where each value moves: an element at row r, column c ends up at row c, column n - 1 - r after a clockwise rotation.
- Try decomposing the rotation into two simpler in-place operations instead of moving every value directly to its final position.