Organize Matrix Rings by Sorting Perimeters
Arrays & HashingAuto-graded · 22 test casesLast 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:
- Collect all elements in that ring by traversing clockwise starting from the top-left corner of the ring.
- Sort these elements in ascending order.
- 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 <= 100wheremis the number of rows andnis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution processes the matrix ring by ring, from outermost to innermost. Each ring is a rectangular perimeter defined by four boundaries: top row, bottom row, left column, and right column.
For each ring:
- Extract coordinates clockwise: Starting from the top-left corner, traverse the top edge (left to right), right edge (top to bottom), bottom edge (right to left), and left edge (bottom to top). Special care is needed for degenerate rings that collapse to a single row or column to avoid visiting cells twice.
- Collect and sort values: Gather the values at these coordinates and sort them in ascending order.
- Write back: Place the sorted values back at the same coordinates in the same clockwise order.
After processing a ring, shrink the boundaries inward by one on all sides and repeat until no cells remain.
Edge Case Handling
- Single row ring (
top == bottom): Only traverse left to right on that row - Single column ring (
left == right): Only traverse top to bottom on that column - Single cell ring: Naturally handled by the single row case
Correctness
Each cell belongs to exactly one ring based on its minimum distance from any edge. The clockwise traversal ensures no cell is visited twice within a ring: the top edge takes both top corners, the right edge takes the bottom-right corner, the bottom edge takes the bottom-left corner, and the left edge stops before reaching the top-left again. The guards prevent double-counting in collapsed rings.
Complexity
- Time: O(N log N) where N = m × n. We visit each cell once during extraction and write-back (O(N)), and sort each ring independently. The total sorting cost is at most O(N log N) since all rings combined contain N elements.
- Space: O(N) for the output matrix, plus O(max ring size) = O(m + n) for temporary storage of one ring's values.
from typing import List
def organize_matrix_rings(matrix: List[List[int]]) -> List[List[int]]:
if not matrix or not matrix[0]:
return matrix
result = [row[:] for row in matrix]
m, n = len(result), len(result[0])
layer = 0
while layer < (min(m, n) + 1) // 2:
top, bottom = layer, m - 1 - layer
left, right = layer, n - 1 - layer
positions = []
if top == bottom:
for c in range(left, right + 1):
positions.append((top, c))
elif left == right:
for r in range(top, bottom + 1):
positions.append((r, left))
else:
for c in range(left, right + 1):
positions.append((top, c))
for r in range(top + 1, bottom + 1):
positions.append((r, right))
for c in range(right - 1, left - 1, -1):
positions.append((bottom, c))
for r in range(bottom - 1, top, -1):
positions.append((r, left))
values = sorted(result[r][c] for r, c in positions)
for (r, c), value in zip(positions, values):
result[r][c] = value
layer += 1
return result