You are given matrix, a square grid of numbers with n rows and n columns, standing for an image. Turn it a quarter turn clockwise.
Change matrix itself: the top row should end up as the right-hand column, and so on. Your function returns nothing. The real task is to do this without building a second n × n grid.
Example 1
Input: matrix = [[2, 4, 6], [8, 1, 3], [5, 7, 9]] Output: [[5, 8, 2], [7, 1, 4], [9, 3, 6]] Why: the top row 2, 4, 6 becomes the right column
2 more examples and the constraints
Example 2
Input: matrix = [[1, 2], [3, 4]] Output: [[3, 1], [4, 2]] Why: each corner moves one corner clockwise
Example 3
Input: matrix = [[7]] Output: [[7]] Why: a single cell turns into itself
Constraints
- matrix has n rows and n columns
- 1 ≤ n ≤ 20
- Every value is between −1,000 and 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy, then write backO(n²)
- Transpose + reverse rowsO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for a 20 × 20 matrix | Verdict |
|---|---|---|---|
| Copy, then write back | O(n²) | Works; breaks the in-place rule | |
| Transpose + reverse rows | O(n²) | Best; in place |
n = number of rows (and columns). The bar compares extra memory, since both take O(n²) time.
Edge cases to test
- One cell. [[7]] stays [[7]]; the loops do nothing.
- Odd size. In a 3 × 3 or 5 × 5 grid, the centre cell never moves.
- Even size. A 2 × 2 or 4 × 4 grid has no centre; every cell moves.
- Repeated values. A grid of all 5s looks unchanged, which can hide a wrong formula in a test.
Common mistakes
- Transposing over the whole grid instead of only c > r, which swaps every pair twice and undoes the work.
- Reversing columns instead of rows, which turns the image counter-clockwise.
- Writing values straight into their new place without a copy or a swap, which overwrites values not read yet.
How to talk through it
- 1Clarify. Clockwise or counter-clockwise? Is it always square? Must it be in place?
- 2Find the formula. Row r ends up as column n − 1 − r. With a copy that is a few lines, but it costs O(n²) memory.
- 3Split the turn. A quarter turn is a transpose then a row flip; both are pure swaps.
- 4Code it. Swap only above the diagonal, then reverse each row.
- 5Test out loud. Run the 2 × 2 and a 3 × 3 with distinct values before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?