Problem · Matrix

Sort Concentric Matrix Rings

Learn this problem
MediumxAI logoxAIFULLTIMEOA

Problem statement

Given an n x n integer matrix, process each concentric ring independently. A ring is identified by its layer k, whose corners are (k, k) and (n - 1 - k, n - 1 - k).

Traverse a non-singleton ring clockwise beginning at its top-left cell: across the top edge, down the right edge, across the bottom edge from right to left, and up the left edge. Visit every ring cell exactly once. Sort that ring's values in nondecreasing order and write them back along the same traversal. If n is odd, the center cell is a singleton ring and remains unchanged.

Return the transformed matrix. Do not mix values between different rings.

Function

sortConcentricRings(matrix: int[][]) → int[][]

Examples

Example 1

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

The outer clockwise traversal contains [9,1,8,7,4,3,6,2]. Writing its sorted values [1,2,3,4,6,7,8,9] along the same path gives the result; the center 5 stays fixed.

Example 2

matrix = [[4,1],[3,2]]return = [[1,2],[4,3]]

The only ring is traversed as [4,1,2,3], then replaced by [1,2,3,4].

Constraints

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

More xAI problems

drafts saved locally
public int[][] sortConcentricRings(int[][] matrix) {
    // Write your code here.
}
matrix[[9,1,8],[2,5,7],[6,3,4]]
expected[[1,2,3],[9,5,4],[8,7,6]]
checking account