KatInterview

Organize Matrix Rings by Sorting Perimeters

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingmatrixtraversalsorting

Last updated

Tests matrix traversal and boundary extraction by sorting each rectangular ring of a matrix independently in clockwise order.

You are given an m x n matrix of integers. Your task is to sort each rectangular ring (perimeter) of the matrix independently.

A ring is defined as the perimeter of a rectangular boundary. The outermost ring consists of all cells on the matrix border. After removing the outermost ring, the next ring is the border of what remains. This continues inward until no cells are left.

For each ring:

  1. Collect all elements in that ring by traversing clockwise starting from the top-left corner of the ring.
  2. Sort these elements in ascending order.
  3. Place the sorted elements back into the ring by writing them clockwise starting from the top-left corner.

The clockwise traversal order for a ring is: top edge (left to right), right edge (top to bottom), bottom edge (right to left), left edge (bottom to top).

Return the modified matrix.

Constraints

  • 1 <= m, n <= 100 where m is the number of rows and n is the number of columns
  • Matrix elements are integers (may be negative or contain duplicates)
  • The input matrix must not be modified; return a new matrix
  • Handle degenerate cases where a ring collapses to a single row, single column, or single cell

Examples

Example 1

Input: organize_matrix_rings([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

Output: [[1, 2, 3], [9, 5, 4], [8, 7, 6]]

Example 2

Input: organize_matrix_rings([[1, 2], [3, 4]])

Output: [[1, 2], [4, 3]]

Hints

Hint 1

Identify each ring by its boundaries: top row, bottom row, left column, and right column indices that shrink as you move inward.

Hint 2

Extract ring elements by walking clockwise: traverse the top row, then right column, then bottom row (if it exists), then left column (if it exists).

Hint 3

Use the same coordinate sequence for both extracting values and writing sorted values back to ensure consistency.