S2Q2 · Rotate Matrix Clockwise 90 Degrees¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: column j of the original (read bottom to top) becomes row j of the rotated matrix.
m, n = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(m)]
for j in range(n):
row = [matrix[m - 1 - i][j] for i in range(m)]
print(*row)
Key rules:
- Original m × n → rotated n × m
- Rotated row j = original column j read from bottom to top
- matrix[m-1-i][j] gives column j from row m-1 down to row 0
Problem Statement¶
Problem (I/O type)
Read an m × n matrix. Print the n × m matrix rotated 90 degrees clockwise.
Example:
3 3
1 2 3
4 5 6
7 8 9
7 4 1
8 5 2
9 6 3
Understanding clockwise rotation¶
For a 90° clockwise rotation: each column of the original becomes a row of the result, reading from bottom to top.
Original (3×3): Rotated (3×3):
1 2 3 7 4 1 ← col 0 bottom→top: 7,4,1
4 5 6 → 8 5 2 ← col 1 bottom→top: 8,5,2
7 8 9 9 6 3 ← col 2 bottom→top: 9,6,3
Formula: rotated[j][i] = original[m-1-i][j]
Tracing the 3×3 example¶
Original column 0 = [1, 4, 7], bottom to top = [7, 4, 1] → first row of output ✓
Original column 1 = [2, 5, 8], bottom to top = [8, 5, 2] → second row ✓
Original column 2 = [3, 6, 9], bottom to top = [9, 6, 3] → third row ✓
Solution approaches¶
Key takeaways¶
Column j (bottom to top) → row j of rotated matrix
This is the defining property of a 90° clockwise rotation. matrix[m-1-i][j] picks element from column j, counting rows from the bottom (i=0 → last row, i=m-1 → first row).
zip(*matrix[::-1]) - the two-liner trick
Reverse the rows (matrix[::-1]), then transpose (zip(*...)). These two operations together achieve a 90° clockwise rotation. Memorise this pattern - it works for any rectangular matrix.
Output is n × m when input is m × n
Rotating a 3×4 matrix clockwise gives a 4×3 matrix. The number of output rows = original number of columns (n), and the number of output columns = original number of rows (m).