FastPrepCenter-Outward Number Spiral

Center-Outward Number Spiral

ZipRecruiter logoZipRecruiter● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a positive odd integer n, construct an n by n matrix containing every integer from 1 through n * n.

Place 1 in the center cell. Continue with consecutive integers while moving in an outward spiral:

  1. Move down first.
  2. Turn right relative to the current movement after completing each leg, so the directions repeat as down, left, up, right.
  3. Increase the leg length after every two legs.
  4. Stop after placing n * n.

Return the completed matrix.

Function

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

Examples

Example 1

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

The spiral starts at the center with 1, moves down to 2, then expands through left, up, and right turns until 9 reaches the bottom-right corner.

Example 2

n = 1return = [[1]]

A one-cell matrix contains only the center value 1.

Constraints

  • 1 <= n <= 99
  • n is odd.

More ZipRecruiter problems

See ZipRecruiter hiring insights
public int[][] centerOutwardSpiral(int n) {
    // Write your solution here.
}
n3
expected[[5,6,7],[4,1,8],[3,2,9]]
Checking account…