Rotate a Matrix
A matrix is a list of rows, each row a list. Write rotate_matrix(matrix) that returns a new matrix rotated 90 degrees clockwise. The matrix may be rectangular, and may be empty.
[[1, 2], [3, 4]] becomes [[3, 1], [4, 2]].
Understand the problem
Find where the first column goes.
After a clockwise turn, where does the first column [1, 3] of [[1, 2], [3, 4]] end up?
- As the first row, reversed:
[3, 1] - As the first row:
[1, 3] - As the last row
Turning clockwise, the left side of the picture becomes the top, read right to left. So the first column, read from the bottom up, is the new first row: [3, 1].
What does list(zip(*[[1, 2], [3, 4]])) give?
[(1, 2), (3, 4)][(1, 3), (2, 4)][(1, 4), (2, 3)]
* unpacks the rows into arguments, so zip pairs the first items together, then the second items: that is the transpose (rows become columns). The results are tuples.
Write the solution
Return a list of lists (not tuples).
def rotate_matrix(matrix):
# Write your code here.
pass
Hint 1: a question to ask yourself
A clockwise turn is a transpose followed by one more flip. Which flip?
Hint 2: the shape of the answer
Reverse the order of the rows (matrix[::-1]), then transpose with zip(*...), and turn each result tuple back into a list.
Reflect
Solution
def rotate_matrix(matrix):
return [list(row) for row in zip(*matrix[::-1])]
Another way: build each new row by hand
def rotate_matrix(matrix):
if not matrix:
return []
rows, cols = len(matrix), len(matrix[0])
return [[matrix[rows - 1 - r][c] for r in range(rows)] for c in range(cols)]
What this tests: zip(*...) (the transpose idiom), slicing with [::-1], comprehensions, and the difference between tuples and lists.
How to remember it: clockwise = reverse the rows, then transpose. Counter-clockwise = transpose, then reverse the rows (or the other way round with the columns).
The result type matters: zip gives tuples, and (3, 1) != [3, 1] in Python. The list(row) converts them, because the task asks for lists.
Cost: O(rows x columns).
What an interviewer might ask next: Rotate a square matrix in place with O(1) extra space. (Transpose in place, then reverse each row.)
VISIBLE = 3
CASES = [
(([[1, 2], [3, 4]],), [[3, 1], [4, 2]], 'a 2 by 2 matrix'),
(([[1, 2, 3], [4, 5, 6]],), [[4, 1], [5, 2], [6, 3]], 'a rectangle'),
(([[1]],), [[1]], 'one cell'),
(([],), [], 'an empty matrix'),
(([[1, 2, 3]],), [[1], [2], [3]], 'one row'),
(([[1], [2], [3]],), [[3, 2, 1]], 'one column'),
(([[1, 2, 3], [4, 5, 6], [7, 8, 9]],), [[7, 4, 1], [8, 5, 2], [9, 6, 3]], 'a 3 by 3 matrix'),
]