Matrices Flashcards
(5 cards)
What is the pattern and when is it used?
Processes 2D grid with traversal or manipulation.
Use Case: Grid search, transformations.
Example: [No LeetCode match, course example: Spiral Matrix]. Action: Verbalize use case aloud.
What are the key steps?
- Define boundaries (top, bottom, left, right).
- Traverse layer by layer, update boundaries.
- Handle remaining rows/columns.
Action: Explain steps for Spiral Matrix aloud.
How does it apply to Spiral Matrix?
Return elements in spiral order.
Approach: Traverse boundaries, shrink after each direction.
Example: Spiral Matrix. Action: Verbalize solution logic aloud.
What are the complexity and gotchas?
Time: O(m*n), Space: O(1).
Gotchas: Empty matrix, single row/column.
Action: List edge cases for Spiral Matrix aloud.
Provide a visual or code example.
```python
from typing import List
def spiral_order(matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for j in range(left, right + 1):
result.append(matrix[top][j])
top += 1
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
if top <= bottom:
for j in range(right, left - 1, -1):
result.append(matrix[bottom][j])
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
~~~