59. Spiral Matrix II

Spiral Matrix II (LeetCode 59) is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Array/Matrix Manipulation Patterns pattern, in the Spiral Traversal subpattern.

How to solve Spiral Matrix II

Spiral Matrix II is a Spiral Matrix Traversal problem, part of Array/Matrix Manipulation Patterns. Master spiral traversal pattern for 2D matrices. Learn to traverse matrices in spiral order for interview problems.

Work towards the solution in these steps:

  1. Consider how you can represent the matrix and the order in which elements should be filled using a systematic approach.
  2. Think about maintaining boundaries for the rows and columns to control the spiral traversal and when to change direction.
  3. Try updating the boundaries after completing each side of the spiral to prevent overwriting elements and to move inward.

The reference solution runs in O(n^2) time and O(1) space.

The Spiral Matrix II solution and editorial walks through the full approach with reference code.

Problem statement

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1: Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2: Input: n = 1 Output: [[1]]

Constraints: 1 <= n <= 20

Topics and companies

Topics: Array.

Reported in interviews at Microsoft.

How to practise Spiral Matrix II on Thita.ai

Starter code is provided in C, C#, C++, dart, elixir, erlang, Go, Java, JavaScript, Kotlin, PHP, Python, python3, racket, Ruby, Rust, Scala, Swift and TypeScript. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n^2) time and O(1) space.

Open Spiral Matrix II in the code editor, or read the Spiral Matrix II editorial for a worked solution with its approach and complexity analysis.

Where Spiral Matrix II sits in the DSA pattern sheet

Problems related to Spiral Matrix II

Other problems that use the same Spiral Traversal and Array/Matrix Manipulation Patterns techniques:

Spiral Matrix II FAQ

What is the LeetCode number of Spiral Matrix II?

Spiral Matrix II is LeetCode problem 59, rated Medium.

What pattern is used to solve Spiral Matrix II?

Spiral Matrix II is a Spiral Matrix Traversal problem. It belongs to the Array/Matrix Manipulation Patterns pattern, in the Spiral Traversal subpattern.

What is the time complexity of Spiral Matrix II?

The reference solution runs in O(n^2) time and O(1) space.

Which companies ask Spiral Matrix II?

Spiral Matrix II has been reported in interviews at Microsoft.

Preparing this workspace.