LeetCode #59 Spiral Matrix II

Medium

Len Chen
1 min readOct 6, 2018

Problem

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

Example:

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

Solution

Start at (0, 0) and put in value of each point by iterating right, down, left and top directions.

Complexity

It’s trivial that we visit each point once so it’s time complexity is O(n²) which is also it’s space complexity because of saving result in a matrix.

--

--

Len Chen
Len Chen

Responses (2)