MediumNo. 2326

Spiral Matrix IV — LeetCode 2326 Python Solution

Topics
Array, Linked List, Matrix, Simulation
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

PythonSolution
# 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

Time
O(m × n)
Space · auxiliary
O(m × n)where m and n represent the number of rows and columns of the matrix, respectively

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

Related problems
No.ProblemDifficulty
0054Spiral MatrixMedium
2181Merge Nodes in Between ZerosMedium
0019Remove Nth Node From End of ListMedium
0021Merge Two Sorted ListsEasy
0024Swap Nodes in PairsMedium
0025Reverse Nodes in k-GroupHard

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 × n).

What is the space complexity of LeetCode 2326. Spiral Matrix IV?

The Python solution on this page uses O(m × 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.

Free to download. Check it runs on your machine, then pick a plan.