Katkat

Sort Every Concentric Matrix Border Clockwise

ByteDanceSoftware Engineer · Online Assessment

Last updated

Sort the values on every concentric border of a rectangular matrix and write them back clockwise from each border's top-left cell. Traverse corners exactly once, preserve interior layer boundaries, handle single-row or single-column centers, and leave the input unchanged.

Problem

For each concentric border of a rectangular integer matrix, sort that border's values in ascending order and write them back clockwise starting at the border's top-left cell. Process every valid border through the center and return the transformed matrix.

Function Contract

Implement sort_matrix_borders(matrix) -> list[list[int]]. Do not mutate the input.

Constraints

  • 1 <= rows, columns <= 200 and all rows have equal length.
  • Border k has top row k, bottom row rows-1-k, left column k, and right column columns-1-k.
  • Clockwise order is top left-to-right, right top-to-bottom, bottom right-to-left, then left bottom-to-top, without visiting a cell twice.
  • A one-row or one-column center is one border vector.

Examples

  • [[4,3],[2,1]] returns [[1,2],[4,3]] because clockwise cells are top-left, top-right, bottom-right, bottom-left.
  • A one-row matrix is returned as that row sorted ascending.

Edge Cases

  • Odd dimensions can leave one center cell.
  • A rectangular center may be a one-row or one-column vector.
  • Duplicates and negative values retain their multiplicities.

Hints

Hint 1

Enumerate coordinates first: Generate each border's coordinate sequence once, collect and sort its values, then zip the sorted values back to those coordinates.