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.
Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.
Return the generated matrix.
Example 1:
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.
Example 2:
Input: m = 1, n = 4, head = [0,1,2] Output: [[0,1,2,-1]] Explanation: The diagram above shows how the values are printed from left to right in the matrix. The last space in the matrix is set to -1.
Constraints:
1 <= m, n <= 1051 <= m * n <= 105[1, m * n].0 <= Node.val <= 1000Problem Overview: Given an m x n matrix and the head of a singly linked list, place the linked list values into the matrix in spiral order starting from the top-left corner. If the linked list runs out of values before the matrix is filled, the remaining cells must contain -1.
The task is essentially a spiral traversal simulation where values are consumed from a linked list and written into a matrix. The tricky part is managing boundaries correctly while stopping when the linked list is exhausted.
Approach 1: Boundary Triggered Spiral Traversal (O(mn) time, O(1) space)
Maintain four boundaries: top, bottom, left, and right. Traverse the matrix in four directions: left→right across the top row, top→bottom along the right column, right→left across the bottom row, and bottom→top along the left column. After each directional pass, shrink the corresponding boundary. During each step, assign the current linked list value and advance the pointer. If the list becomes null, fill remaining cells with -1. The matrix is filled exactly once, so the runtime is O(mn) with O(1) extra space beyond the output matrix.
This approach works well because spiral traversal naturally maps to shrinking boundaries. The logic is straightforward: write values while the current boundary range is valid and the linked list still has nodes.
Approach 2: Layer-by-Layer Spiral Traversal (O(mn) time, O(1) space)
Instead of triggering direction changes dynamically, treat the spiral as a sequence of layers. Each layer has four segments: top row, right column, bottom row, and left column. Iterate through each segment of the layer and place values from the linked list. After completing a layer, move inward by incrementing top and left, and decrementing bottom and right. Continue until the boundaries cross or the linked list ends.
The key idea is that each spiral loop forms a rectangular ring. Processing these rings sequentially keeps the logic structured and predictable. Like the previous method, each matrix cell is written once, giving O(mn) time and constant auxiliary space.
Both strategies rely on simple array indexing and direct simulation. No extra data structures are required besides the input linked list pointer.
Recommended for interviews: Boundary Triggered Spiral Traversal is the version most interviewers expect. It demonstrates control over spiral traversal patterns and careful boundary updates. The layer-by-layer approach shows the same understanding but organizes the logic around rectangular rings, which some developers find easier to reason about.
This approach traverses the matrix in a spiral order by systematically altering the direction when encountering the boundary or an already filled space. Start with the initial direction as 'right'. Change direction to 'down', 'left', 'up' as necessary when a boundary or an already filled cell is encountered.
The provided Python code defines a function spiralMatrix that takes the dimensions m, n and the head of a linked list. It begins by creating a m x n matrix initialized with -1. The spiral movement is driven by the dirs array, which holds possible movement directions. For each direction change, we ensure it keeps within valid boundaries or filled cell conditions. This implementation guarantees that the matrix is filled in a proper spiral order, transitioning directions when necessary.
In this approach, we fill the matrix in a spiral order by completing one 'layer' of the spiral at a time. Start filling from the outer layer to the inner layers progressively until the entire matrix is filled. Each layer comprises four segments: top row, right column, bottom row, and left column.
The Java implementation manages a layer by tracking the limits of the current upward, downward, leftward, and rightward possible moves. The solution fills all available cells in these 'layers', transitioning from one direction to the next only after fully exhausting entries along the current path, and proceeds inward. The method completes filling the complete list coupled with the matrix traversal ensuring optimal manipulation through nested loops guarding respective limits.
We define a two-dimensional array ans to store the elements in the linked list, initially all filled with -1. We define three variables i, j, k, representing the current row, column, and direction respectively. We define an array dirs to represent the offsets of the four directions.
Then we start traversing the linked list. Each time we traverse a node, we fill the current node's value into ans[i][j], then update the linked list pointer. If the linked list is empty, it means all elements have been filled and we exit the loop.
Otherwise, we need to find the position of the next element. We can calculate the next position (x, y) through the current position (i, j) and the current direction k. If (x, y) is within the range of the matrix, and ans[x][y] is -1, it means (x, y) has not been filled yet, so we take (x, y) as the next position. Otherwise, we need to change the direction.
After traversing the linked list, we get a spiral matrix and return it.
The time complexity is O(m times n), and the space complexity is O(m times n), where m and n represent the number of rows and columns of the matrix, respectively.
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Boundary Triggered Spiral Traversal |
|
| Layer-by-Layer Spiral Traversal |
|
| Simulation | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Boundary Triggered Spiral Traversal | O(mn) | O(1) | General solution for spiral matrix simulation; easiest to implement during interviews |
| Layer-by-Layer Spiral Traversal | O(mn) | O(1) | When you prefer structured traversal using concentric matrix layers |
Spiral Matrix IV - Leetcode 2326 - Python • NeetCodeIO • 6,803 views views
Watch 9 more video solutions →Practice Spiral Matrix IV with our built-in code editor and test cases.
Practice on FleetCode