Rotate square array elements
Filed under Amazon
Free read 3 of 3Process concentric layers defined by top, bottom, left, right boundaries starting from ring 0 to n // 2 - 1.
The question
Given an n x n 2D matrix, rotate elements in each concentric ring clockwise by one position in-place.
Constraints
- n is between 1 and 100.
- -10^4 <= matrix[i][j] <= 10^4
Examples
- Input
- matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- Output
- [[4, 1, 2], [7, 5, 3], [8, 9, 6]]
- Why
- Outer ring elements shift clockwise by one step. The center element 5 remains untouched.
Approach
Process concentric layers defined by top, bottom, left, right boundaries starting from ring 0 to n // 2 - 1.
Save the top-left element. Shift left column up, bottom row left, right column down, and top row right, then place saved element into top-left + 1.
1x1 matrix requires no movement. Handle odd n where central element is untouched.
Tips
- What they are testing: Tests 2D matrix index manipulation, boundary tracking, and in-place swapping.
- Common mistake: Overwriting corner values during boundary traversal without temporarily caching them.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.