Sort Each Border of a Matrix
A rectangular matrix is made of concentric borders: the outer ring, the ring inside it, and so on to the centre. For each border, sort its values in ascending order and write them back clockwise, starting at the border's top-left cell. Return the transformed matrix without mutating the input.
Clockwise means: along the top row left to right, down the right column, along the bottom row right to left, then up the left column, visiting no cell twice. A centre that is a single row or a single column is one border, written left to right or top to bottom.
[[9, 8, 7], [[1, 2, 3], [6, 5, 4], -> [9, 5, 4], [3, 2, 1]] [8, 7, 6]] [[4, 3], [[1, 2], [2, 1]] -> [4, 3]]
Up to 200 rows and 200 columns.
Hints
Hint 1
Separate the two concerns: first produce the list of coordinates of one border in clockwise order, then sort values and assign them along that list.
Hint 2
Border k spans rows k to rows - 1 - k and columns k to cols - 1 - k. Stop when either range is empty.
Hint 3
When the border is a single row, do not walk the bottom row; when it is a single column, do not walk back up the left column.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.