Leetcode #2326: Spiral Matrix IV
In this guide, we solve Leetcode #2326 Spiral Matrix IV in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Linked List, Matrix, Simulation
Intuition
Linked list problems often require pointer manipulation rather than extra memory.
Two-pointer techniques expose cycles, midpoints, or reordering patterns.
Approach
Traverse with fast/slow pointers or reverse sublists when needed.
Maintain invariants carefully to avoid losing nodes.
Steps:
- Traverse with pointers.
- Reverse or split if required.
- Reconnect nodes correctly.
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.
Note that the remaining spaces in the matrix are filled with -1.
Python Solution
# 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
The time complexity is , and the space complexity is , where and represent the number of rows and columns of the matrix, respectively. The space complexity is , where and represent the number of rows and columns of the matrix, respectively.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.