Problem · Matrix

Sort Every Matrix Border Layer

Learn this problem
MediumCapital OneOA

Problem statement

Given a rectangular integer matrix, sort the values on every concentric border layer independently in ascending order.

For each layer, visit its cells clockwise beginning at that layer's top-left cell:

  1. Traverse the top edge from left to right.
  2. Traverse the right edge from top to bottom, excluding the already visited top-right cell.
  3. If the layer has more than one row, traverse the bottom edge from right to left, excluding the already visited bottom-right cell.
  4. If the layer has more than one column, traverse the left edge from bottom to top, excluding both already visited corner cells.

Collect the values in this order, sort them in ascending order, and write them back along the same clockwise path. Continue from the outermost layer toward the center. A layer consisting of one row, one column, or one cell follows the same rule without visiting any cell twice.

Return the matrix after every layer has been sorted.

Function

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

Examples

Example 1

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

The outer layer is read as [4,1,3,8,5,6,7,2]. Writing its sorted values [1,2,3,4,5,6,7,8] along the same path produces the returned matrix. The center value 9 forms a one-cell layer and remains unchanged.

Example 2

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

This two-row matrix has one layer. Its clockwise order is [8,1,6,2,3,5,4,7], so the values 1 through 8 are written in ascending order around that path.

Example 3

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

A single-column layer is visited from top to bottom exactly once, then sorted in that order.

Constraints

  • 1 <= matrix.length <= 200
  • 1 <= matrix[i].length <= 200
  • Every row has the same length.
  • -10^9 <= matrix[i][j] <= 10^9

More Capital One problems

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