Question presented to candidate: "You are given an n by n matrix as a Python list of lists, for example an image. Rotate it 90 degrees clockwise, in place: modify the given lists rather than returning a new matrix."
What a strong answer should cover:
- The mapping: cell
(r, c)goes to(c, n - 1 - r); a copy-based version is easy but O(n²) extra space. - Transpose (swap
m[i][j]withm[j][i]forj > ionly), then reverse each row; O(n²) time, O(1) extra space. - The alternative four-way swap per layer, and the counter-clockwise variant (transpose, then reverse the row order).
- Only square matrices can be rotated in place; R×C becomes C×R.
- Python specifics:
list(zip(*m[::-1]))is a neat one-liner but builds new tuples,row.reverse()is in place whilerow = row[::-1]only rebinds a name, and[[0] * n] * ncreates n references to the same row.
Clarifying questions expected:
- "Clockwise or counter-clockwise, and is it always square?"
- "Is a new matrix acceptable, or must it be in place?"
Code / implementation expected: Yes — a Python rotate(matrix) that transposes and reverses rows in place.