FastPrepSort Matrix Borders

Sort Matrix Borders

Susquehanna International Group (SIG) logoSusquehanna International Group (SIG)● MediumFULLTIMEOA
Learn

Problem statement

Given matrix, an n x m rectangular matrix of integers, let's define its 0-border as the union of its leftmost and rightmost columns, as well as its top and bottom rows. A vector's 0-border is the vector itself.

If we were to remove the matrix's 0-border, then the 0-border of the resulting matrix can be defined as the 1-border of the original matrix. We can continue this way to define the 2-border, 3-border, etc, until we reach the center of the matrix.

For each valid k, your task is to sort the elements in each k-border and place them clockwise in ascending order, starting from the top-left corner.

Note: You are not expected to provide the most optimal solution, but a solution with time complexity not worse than O(n * m * (n + m)) will fit within the execution time limit.

Function

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

Examples

Example 1

matrix = [[9,7,-4,5],[1,6,2,-6],[12,20,2,0]]return = [[-6,-4,0,1],[20,2,6,2],[12,9,7,5]]

The outer border is sorted and rewritten clockwise as [-6, -4, 0, 1, 2, 5, 7, 9, 12, 20]. The inner one-row border [6, 2] becomes [2, 6].

Example 2

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

The only border is one column, so it is visited from top to bottom and sorted in that order.

Constraints

  • 1 <= matrix.length <= 100
  • 1 <= matrix[i].length <= 100
  • Every row has the same length.
  • -100 <= matrix[i][j] <= 100

Source note: The source screenshot preserves the border-order example, constraints, output contract, and Python reference.

More Susquehanna International Group (SIG) problems

See Susquehanna International Group (SIG) hiring insights
public int[][] solution(int[][] matrix) {
    // Write your code here.
}
matrix[[9,7,-4,5],[1,6,2,-6],[12,20,2,0]]
expected[[-6,-4,0,1],[20,2,6,2],[12,9,7,5]]
Checking account…