Generate a Spiral Matrix

Quick Overview

Generate an n by n matrix filled with the integers from 1 through n squared in clockwise spiral order, following the cited problem.

Generate a Spiral Matrix

Company: Pinduoduo

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Technical Screen

# Generate a Spiral Matrix Implement `generate_spiral_matrix(n: int) -> list[list[int]]`. Return an `n` by `n` matrix containing every integer from `1` through `n * n` exactly once, arranged in clockwise spiral order. Start with `1` in the top-left cell, move right across the top boundary, and turn clockwise whenever the next cell would leave the current unfilled boundary. ## Valid Input Domain - `n` is a positive integer. ## Constraints - `1 <= n <= 1,000` - `n * n` fits in a signed 32-bit integer. ## Public Examples ### Example 1 Input: `3` Output: `[[1, 2, 3], [8, 9, 4], [7, 6, 5]]` ### Example 2 Input: `1` Output: `[[1]]` ```hint Shrink four boundaries After completing one side of the spiral, move the corresponding unfilled boundary inward. ```

Overview: Generate an n by n matrix filled with the integers from 1 through n squared in clockwise spiral order, following the cited problem.

|Home/Coding & Algorithms/Pinduoduo
Pinduoduo logo
Pinduoduo
Aug 19, 2026
easySoftware EngineerTechnical ScreenCoding & Algorithms
1
0

Generate a Spiral Matrix

Implement generate_spiral_matrix(n: int) -> list[list[int]].

Return an n by n matrix containing every integer from 1 through n * n exactly once, arranged in clockwise spiral order. Start with 1 in the top-left cell, move right across the top boundary, and turn clockwise whenever the next cell would leave the current unfilled boundary.

Valid Input Domain

  • n is a positive integer.

Constraints

  • 1 <= n <= 1,000
  • n * n fits in a signed 32-bit integer.

Public Examples

Example 1

Input: 3

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

Example 2

Input: 1

Output: [[1]]

Submit Your Answer to Earn 20XP

Sign in to leave a comment

Loading comments...