Spiral Matrix IV — LeetCode 2326 Python Solution

MediumArrayLinked ListMatrixSimulation
Problem
#2326
Reading time
4 min

The problem

You are given two integers m and n, which represent the dimensions of a matrix. You are also given the head of a linked list of integers.

Example

Input
m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
Output
[[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]
Explanation
The diagram above shows how the values are printed in the matrix.

Python solution

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
        ans = [[-1] * n for _ in range(m)]
        i = j = k = 0
        dirs = (0, 1, 0, -1, 0)
        while 1:
            ans[i][j] = head.val
            head = head.next
            if head is None:
                break
            while 1:
                x, y = i + dirs[k], j + dirs[k + 1]
                if 0 <= x < m and 0 <= y < n and ans[x][y] == -1:
                    i, j = x, y
                    break
                k = (k + 1) % 4
        return ans

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n), where m and n represent the number of rows and columns of the matrix, respectively auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 2326. Spiral Matrix IV is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2326. Spiral Matrix IV?
LeetCode 2326. Spiral Matrix IV is rated Medium on LeetCode.
What is the time complexity of LeetCode 2326. Spiral Matrix IV?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 2326. Spiral Matrix IV?
The Python solution on this page uses O(m \times n), where m and n represent the number of rows and columns of the matrix, respectively auxiliary space.
What topics does LeetCode 2326. Spiral Matrix IV cover?
LeetCode 2326. Spiral Matrix IV is tagged Array, Linked List, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview