Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.
Return an array of coordinates representing the positions of the grid in the order you visited them.
Example 1:
Input: rows = 1, cols = 4, rStart = 0, cStart = 0 Output: [[0,0],[0,1],[0,2],[0,3]]
Example 2:
Input: rows = 5, cols = 6, rStart = 1, cStart = 4 Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
Constraints:
1 <= rows, cols <= 1000 <= rStart < rows0 <= cStart < colsProblem summary: 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. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid. Return an array of coordinates representing the positions of the grid in the order you visited them.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
1 4 0 0
5 6 1 4
spiral-matrix)spiral-matrix-ii)spiral-matrix-iv)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #885: Spiral Matrix III
class Solution {
public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int cnt = rows * cols;
int[][] ans = new int[cnt][2];
ans[0] = new int[] {rStart, cStart};
if (cnt == 1) {
return ans;
}
for (int k = 1, idx = 1;; k += 2) {
int[][] dirs = new int[][] {{0, 1, k}, {1, 0, k}, {0, -1, k + 1}, {-1, 0, k + 1}};
for (int[] dir : dirs) {
int r = dir[0], c = dir[1], dk = dir[2];
while (dk-- > 0) {
rStart += r;
cStart += c;
if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {
ans[idx++] = new int[] {rStart, cStart};
if (idx == cnt) {
return ans;
}
}
}
}
}
}
}
// Accepted solution for LeetCode #885: Spiral Matrix III
func spiralMatrixIII(rows int, cols int, rStart int, cStart int) [][]int {
cnt := rows * cols
ans := [][]int{[]int{rStart, cStart}}
if cnt == 1 {
return ans
}
for k := 1; ; k += 2 {
dirs := [][]int{{0, 1, k}, {1, 0, k}, {0, -1, k + 1}, {-1, 0, k + 1}}
for _, dir := range dirs {
r, c, dk := dir[0], dir[1], dir[2]
for dk > 0 {
rStart += r
cStart += c
if rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols {
ans = append(ans, []int{rStart, cStart})
if len(ans) == cnt {
return ans
}
}
dk--
}
}
}
}
# Accepted solution for LeetCode #885: Spiral Matrix III
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
// Accepted solution for LeetCode #885: Spiral Matrix III
struct Solution;
impl Solution {
fn spiral_matrix_iii(r: i32, c: i32, r0: i32, c0: i32) -> Vec<Vec<i32>> {
let mut res = vec![];
let total = (r * c) as usize;
let directions = vec![(0, 1), (1, 0), (0, -1), (-1, 0)];
let mut d = 0;
let mut step = 1;
let mut i = r0;
let mut j = c0;
let mut k = 0;
while res.len() < total {
if i >= 0 && i < r && j >= 0 && j < c {
res.push(vec![i, j]);
}
i += directions[d].0;
j += directions[d].1;
k += 1;
if k == step {
d += 1;
d %= 4;
k = 0;
if d % 2 == 0 {
step += 1;
}
}
}
res
}
}
#[test]
fn test() {
let r = 1;
let c = 4;
let r0 = 0;
let c0 = 0;
let res = vec_vec_i32![[0, 0], [0, 1], [0, 2], [0, 3]];
assert_eq!(Solution::spiral_matrix_iii(r, c, r0, c0), res);
let r = 5;
let c = 6;
let r0 = 1;
let c0 = 4;
let res = vec_vec_i32![
[1, 4],
[1, 5],
[2, 5],
[2, 4],
[2, 3],
[1, 3],
[0, 3],
[0, 4],
[0, 5],
[3, 5],
[3, 4],
[3, 3],
[3, 2],
[2, 2],
[1, 2],
[0, 2],
[4, 5],
[4, 4],
[4, 3],
[4, 2],
[4, 1],
[3, 1],
[2, 1],
[1, 1],
[0, 1],
[4, 0],
[3, 0],
[2, 0],
[1, 0],
[0, 0]
];
assert_eq!(Solution::spiral_matrix_iii(r, c, r0, c0), res);
}
// Accepted solution for LeetCode #885: Spiral Matrix III
function spiralMatrixIII(rows: number, cols: number, rStart: number, cStart: number): number[][] {
// prettier-ignore
const dir = [[1,0],[0,1],[-1,0],[0,-1]]
let [x, y, i, size] = [cStart, rStart, 0, 0];
const ans: number[][] = [[y, x]];
const total = rows * cols;
while (ans.length < total) {
if (i % 2 === 0) size++;
for (let j = 0; ans.length < total && j < size; j++) {
x += dir[i][0];
y += dir[i][1];
if (0 <= x && x < cols && 0 <= y && y < rows) {
ans.push([y, x]);
}
}
i = (i + 1) % 4;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.