Spiral Matrix II LeetCode Solution

Last updated on January 19th, 2025 at 02:51 am

Here, we see a Spiral Matrix II LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Array

Level of Question

Medium

Spiral Matrix II LeetCode Solution

Spiral Matrix II LeetCode Solution

1. 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]]

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is “Matrix Traversal”. This pattern involves traversing a 2D matrix in a specific order (in this case, a spiral order) to fill or process its elements.

3. Code Implementation in Different Languages

3.1 Spiral Matrix II C++

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
    vector<vector<int>> res(n, vector<int> (n, 1));
    int left, right, top, down, index;
    left = top = index = 0, right = down = n-1;
    while (left <= right && top <= down) {
        for (unsigned int j = left; j <= right; j++)
            res[top][j] = ++index;
        top++;
        for (unsigned int i = top; i <= down; i++)
            res[i][right] = ++index;
        right--;
        for (int j = right; j >= left; j--)
            res[down][j] = ++index;
        down--;
        for (int i = down; i >= top; i--)
            res[i][left] = ++index;
        left++;
    }
    return res;        
    }
};

3.2 Spiral Matrix II Java

class Solution {
    public int[][] generateMatrix(int n) {
	int[][] ret = new int[n][n];
	int left = 0,top = 0;
	int right = n -1,down = n - 1;
	int count = 1;
	while (left <= right) {
		for (int j = left; j <= right; j ++) {
			ret[top][j] = count++;
		}
		top ++;
		for (int i = top; i <= down; i ++) {
			ret[i][right] = count ++;
		}
		right --;
		for (int j = right; j >= left; j --) {
			ret[down][j] = count ++;
		}
		down --;
		for (int i = down; i >= top; i --) {
			ret[i][left] = count ++;
		}
		left ++;
	}
	return ret;        
    }
}

3.3 Spiral Matrix II JavaScript

var generateMatrix = function(n) {
  const M = [...Array(n)].map(() => Array(n).fill(0));
  let x = 0, y = 0, dx = 1, dy = 0;
  for (let i = 1, nn = n**2; i <= nn; ++i) {
    M[y][x] = i;
    if (!M[y + dy] || M[y + dy][x + dx] !== 0)
      [dx, dy] = [-dy, dx];
    x += dx;
    y += dy;
  }
  return M;
};

3.4 Spiral Matrix II Python

class Solution(object):
    def generateMatrix(self, n):
        A = [[0] * n for _ in range(n)]
        i, j, di, dj = 0, 0, 0, 1
        for k in xrange(n*n):
            A[i][j] = k + 1
            if A[(i+di)%n][(j+dj)%n]:
                di, dj = dj, -di
            i += di
            j += dj
        return A

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n2)O(n2)
JavaO(n2)O(n2)
JavaScriptO(n2)O(n2)
PythonO(n2)O(n2)
  • The time complexity is O(n2) because the algorithm processes each element of the matrix exactly once.
  • The space complexity is O(n2) because the matrix itself requires O(n2) space, and no significant additional space is used.
  • The logic for all implementations is similar, with minor syntactic differences based on the language.

Scroll to Top