Problem · Matrix

Traverse Interior Matrix Cells in Row-Major Order

Learn this problem
EasyCitadel logoCitadelINTERNONSITE INTERVIEW

Problem statement

You are given a non-empty rectangular integer matrix matrix. Traverse its interior cells in row-major order and return their values.

A cell is on the boundary when it belongs to the first row, last row, first column, or last column. Interior cells belong to none of those boundary lines.

Visit interior rows from top to bottom and, within each row, visit interior columns from left to right. If the matrix has fewer than three rows or fewer than three columns, return an empty array.

Function

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

Examples

Example 1

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]return = [6,7,10,11]

The interior cells are (1,1), (1,2), (2,1), and (2,2). Row-major traversal returns their values in that order.

Example 2

matrix = [[1,2,3],[4,5,6],[7,8,9]]return = [5]

A three-by-three matrix has exactly one interior cell, the center.

Example 3

matrix = [[1,2,3,4],[5,6,7,8]]return = []

With only two rows, every cell lies on the first or last row, so there are no interior cells.

Constraints

  • 1 <= matrix.length, matrix[0].length <= 1000.
  • matrix.length * matrix[0].length <= 10^6.
  • Every row has the same length.
  • -2^31 <= matrix[row][col] <= 2^31 - 1.

More Citadel problems

drafts saved locally
public int[] traverseInteriorCells(int[][] matrix) {
  // write your code here
}
matrix[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
expected[6,7,10,11]
checking account