← Amazon questions

Rotate square array elements

Filed under Amazon

Free read 3 of 3

Process 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

  1. Process concentric layers defined by top, bottom, left, right boundaries starting from ring 0 to n // 2 - 1.

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.