Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Simulation
Google
Spiral Matrix II

Generate an n×nn \times n matrix filled with numbers from 1 to n2n^2 in spiral order.

Acceptance 0%
Problem Statement

Problem

Given a positive integer nn, create an n×nn \times n matrix and fill it with the integers from 1 to n^2 in clockwise spiral order, starting from the top-left cell and moving right first.

You should return the completed matrix after all numbers have been placed.

Notes

  • The spiral proceeds around the outer layer first, then continues inward.
  • Each number from 1 to n^2 must appear exactly once.
  • When the spiral reaches the center, it should stop after placing the final value.

Input Format

  • A single integer n.

Interpretation

  • Build an n x n grid.
  • Fill cells with 1, 2, 3, ..., n^2 in clockwise spiral order.

Output Format

  • Return an n x n 2D integer array representing the filled spiral matrix.

Constraints

  • 1n1 \le n.
  • The matrix size is n×nn \times n.
  • Every value from 1 to n^2 appears exactly once.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 3

Output

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

Explanation

The numbers are placed in clockwise spiral order starting from the top-left corner.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.