FastPrepRotate Matrix Regions Around the Diagonals

Rotate Matrix Regions Around the Diagonals

Susquehanna International Group (SIG) logoSusquehanna International Group (SIG)● MediumNEW GRADOA
Learn

Problem statement

You are given an n x n integer matrix and an integer turns. The main diagonal and anti-diagonal divide the cells outside the diagonals into top, right, bottom, and left regions.

One turn rotates those four regions clockwise by 90 degrees: every non-diagonal value at (row, column) moves to (column, n - 1 - row). Every cell on either diagonal stays fixed.

Apply exactly turns turns and return the resulting matrix.

Function

rotateMatrixOverDiagonals(matrix: int[][], turns: int) → int[][]

Examples

Example 1

matrix = [[1,2,3,4,5],[2,1,9,6,3],[7,0,4,8,1],[5,2,4,1,9],[6,4,3,2,1]]turns = 1return = [[1,5,7,2,5],[4,1,0,6,2],[3,4,4,9,3],[2,2,8,1,4],[6,9,1,3,1]]

The diagonal values remain in place. Every other value advances clockwise into the next triangular region.

Example 2

matrix = [[1,2,3],[4,5,6],[7,8,9]]turns = 1return = [[1,4,3],[8,5,2],[7,6,9]]

The four off-diagonal values 2, 6, 8, 4 move clockwise, while 1, 3, 5, 7, 9 stay fixed.

Example 3

matrix = [[7]]turns = 3return = [[7]]

The only cell lies on both diagonals, so every turn leaves it unchanged.

Constraints

  • 1 <= n <= 200.
  • matrix.length = matrix[i].length = n.
  • -10^9 <= matrix[i][j] <= 10^9.
  • 1 <= turns <= 4.

More Susquehanna International Group (SIG) problems

See Susquehanna International Group (SIG) hiring insights
public int[][] rotateMatrixOverDiagonals(int[][] matrix, int turns) {
    // write your code here
}
matrix[[1,2,3,4,5],[2,1,9,6,3],[7,0,4,8,1],[5,2,4,1,9],[6,4,3,2,1]]
turns1
expected[[1,5,7,2,5],[4,1,0,6,2],[3,4,4,9,3],[2,2,8,1,4],[6,9,1,3,1]]
Checking account…