Problem · Matrix

Generate a Spiral Matrix

Learn this problem
MediumMicrosoft logoMicrosoftFULLTIMEONSITE INTERVIEW
See Microsoft hiring insights

Problem statement

Given a positive integer n, create an n by n matrix containing the integers from 1 through n * n in clockwise spiral order.

Begin with 1 in the top-left cell and initially move right.

Function

generateMatrix(n: int) → int[][]

Examples

Example 1

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

The values wrap clockwise around the boundary before filling the center cell.

Example 2

n = 1return = [[1]]

A one-cell matrix contains only 1.

Constraints

  • n is positive.
  • n * n fits in a signed integer.

More Microsoft problems

drafts saved locally
public int[][] generateMatrix(int n) {
    // TODO: fill an n by n matrix in clockwise spiral order.
}
n3
expected[[1,2,3],[8,9,4],[7,6,5]]
checking account