FastPrepSort Matrix Borders
Problem · Array

Sort Matrix Borders

Learn this problem
MediumHudson River Trading logoHudson River TradingINTERNOA

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]]

For

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

FastPrep-authored deterministic derivation: The source image shows this example input but is cropped before its output. Applying the visible border-sorting rule gives the executable output shown here.

Constraints

  • FastPrep execution-adapter constraints (not shown in the source image):
  • matrix is non-empty.
  • Every row has the same positive length.
  • Every entry is an integer.

More Hudson River Trading problems

drafts saved locally
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