Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #885: Spiral Matrix III

In this guide, we solve Leetcode #885 Spiral Matrix III 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.

Leetcode

Problem Statement

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Matrix, Simulation

Intuition

Grid problems are easiest when you define clear row/column boundaries.

A consistent traversal order prevents off-by-one errors.

Approach

Iterate by rows, columns, or layers depending on the requirement.

Keep bounds updated as the traversal progresses.

Steps:

  • Define bounds or directions.
  • Visit cells in order.
  • Update result and move bounds.

Example

Input: rows = 1, cols = 4, rStart = 0, cStart = 0 Output: [[0,0],[0,1],[0,2],[0,3]]

Python Solution

class Solution: def spiralMatrixIII( self, rows: int, cols: int, rStart: int, cStart: int ) -> List[List[int]]: ans = [[rStart, cStart]] if rows * cols == 1: return ans k = 1 while True: for dr, dc, dk in [[0, 1, k], [1, 0, k], [0, -1, k + 1], [-1, 0, k + 1]]: for _ in range(dk): rStart += dr cStart += dc if 0 <= rStart < rows and 0 <= cStart < cols: ans.append([rStart, cStart]) if len(ans) == rows * cols: return ans k += 2

Complexity

The time complexity is O(m·n). The space complexity is O(1) to O(m·n).

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.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy