Solving Leetcode Interviews in Seconds with AI: Spiral Matrix II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "59" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
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
Explanation
Here's the solution to generate an n x n matrix filled with elements from 1 to n^2 in spiral order:
High-Level Approach:
- Initialize an n x n matrix with all elements set to 0.
- Iterate through the matrix in a spiral manner, filling in the numbers from 1 to n^2. The spiral traversal can be simulated by defining boundaries (top, bottom, left, right) and moving within these boundaries.
- Update the boundaries as the spiral progresses.
Complexity:
- Runtime Complexity: O(n^2)
- Storage Complexity: O(n^2)
Code
def generateMatrix(n: int) -> list[list[int]]:
"""
Generates an n x n matrix filled with elements from 1 to n^2 in spiral order.
"""
matrix = [[0] * n for _ in range(n)]
num = 1
top, bottom = 0, n - 1
left, right = 0, n - 1
direction = 0 # 0: right, 1: down, 2: left, 3: up
while top <= bottom and left <= right:
if direction == 0: # right
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
elif direction == 1: # down
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
elif direction == 2: # left
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
elif direction == 3: # up
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
direction = (direction + 1) % 4
return matrix