MediumNo. 2326
Spiral Matrix IV — LeetCode 2326 Python Solution
- Pattern
- Linked List
- Topics
- Array, Linked List, Matrix, Simulation
- Reading time
- 4 min
- Source
- leetcode.com
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
# 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 ansComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0054 | Spiral Matrix | Medium |
| 2181 | Merge Nodes in Between Zeros | Medium |
| 0019 | Remove Nth Node From End of List | Medium |
| 0021 | Merge Two Sorted Lists | Easy |
| 0024 | Swap Nodes in Pairs | Medium |
| 0025 | Reverse Nodes in k-Group | Hard |
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.