Obstacle-Aware Clockwise Spiral Walk
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement spiral_with_blockers(matrix: list[list[int]], blocked: list[list[int]]) -> list[int] to simulate a clockwise spiral cursor navigating a rectangular m x n integer grid around impassable obstacles.
Grid rows are indexed 0 through m - 1 from top to bottom, and columns are indexed 0 through n - 1 from left to right. Each entry [r, c] in blocked designates an obstacle coordinate that the cursor can never enter.
Navigation obeys the following deterministic rules:
- Cardinal headings & rotation: The four headings in clockwise sequence are east
(0, +1), south(+1, 0), west(0, -1), and north(-1, 0), wrapping from north back to east. - Passable coordinates: Coordinate
(r, c)is passable when0 <= r < m,0 <= c < n,[r, c]is absent fromblocked, and(r, c)has not yet been visited. - Starting position: Navigation begins at
(0, 0)oriented east. Coordinate(0, 0)is immediately marked visited andmatrix[0][0]is recorded as the first output element. - Advancing & turning: From the current coordinate, inspect the neighbor along the current heading. If passable, advance into that neighbor while keeping the same heading, mark it visited, and append its integer value to the result. Otherwise, rotate the heading 90 degrees clockwise in place and inspect the new neighbor—testing up to all four headings from the current coordinate and stepping along the first passable heading found.
- Stopping: Whenever none of the four cardinal neighbors around the current coordinate is passable, navigation halts immediately. Obstacle values and any remaining unvisited coordinates sealed off elsewhere in the grid are omitted from the output.
Note that passing blocked = [] naturally traces the standard outer-to-inner clockwise spiral across the entire grid.
Examples
Example 1
Input: matrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]], blocked = []
Output: [10, 20, 30, 60, 90, 80, 70, 40, 50]
With zero obstacles, grid borders and already-visited outer cells steer the cursor around the perimeter (10 -> 20 -> 30 -> 60 -> 90 -> 80 -> 70 -> 40) before stepping east into center value 50.
Example 2
Input: matrix = [[2, 4, 6, 8], [1, 3, 5, 7]], blocked = [[0, 2]]
Output: [2, 4, 3, 1]
Starting at 2, the cursor advances east to 4, sees obstacle [0, 2] ahead, rotates south into 3, hits the bottom border and rotates west into 1, and halts at (1, 0) because all four surrounding neighbors are either off-grid or already visited—leaving 8, 5, and 7 unreached.
Example 3
Input: matrix = [[5, 10, 15], [20, 25, 30], [35, 40, 45]], blocked = [[0, 2], [2, 0]]
Output: [5, 10, 25, 40, 45, 30]
After 5 -> 10, obstacle [0, 2] forces a clockwise turn south through 25 -> 40. At (2, 1) facing south, south is off-grid, west is obstacle [2, 0], and north is visited (1, 1), so three 90-degree clockwise rotations point east into 45. Three more rotations at (2, 2) point north into 30, where all four neighbors are unavailable and navigation ends without reaching 20.
Constraints
1 <= m, n <= 100, wherem = len(matrix)andn = len(matrix[0])(every row has lengthn).-10^9 <= matrix[r][c] <= 10^90 <= len(blocked) <= m * n - 1- All
[r, c]pairs inblockedare distinct valid coordinates insidematrix, and[0, 0]never appears inblocked.
Step-by-step walkthrough
Understand the cursor's rules
We receive an
m x ninteger gridmatrixand a list of obstacle coordinatesblocked = [[r, c], ...]. Starting on(0, 0)facing east (right), our cursor advances one cell at a time by repeating one decision loop:- Inspect the neighbor directly ahead along the current heading.
- If that coordinate is passable (within grid bounds, absent from
blocked, and not yet visited), move into it, keep the same heading, and append its integer value to the output. - Otherwise, rotate 90 degrees clockwise in place and inspect again—testing up to all 4 cardinal headings from the current coordinate.
- If all 4 neighbors fail the passability check, halt immediately (leaving any unreachable open cells elsewhere unvisited).
Here is how row and column deltas map to the four clockwise headings:
North (-1, 0) ^ | West (0, -1) <-- (r, c) --> East (0, +1) [initial heading] | v South (+1, 0) Clockwise cycle: East -> South -> West -> North -> EastWhen
blockedis empty, encountering grid borders and previously visited outer rings automatically guides the cursor through the standard inward spiral.Why ring-by-ring boundaries break with obstacles
For an obstacle-free spiral, a common approach tracks four shrinking indices (
top,bottom,left,right) and peels one rectangular frame per loop. Obstacles shatter that rectangular symmetry—look at Example 2 (matrix = [[2, 4, 6, 8], [1, 3, 5, 7]],blocked = [[0, 2]]):col 0 col 1 col 2 col 3 2 ----> 4 [X] 8 (stranded!) | 1 <---- 3 5 7 (stranded!)Obstacle
[0, 2]forces an early southward turn at column1, followed by a westward step into1, where the cursor gets boxed in—leaving8,5, and7stranded on the right half of the grid. Trying to patchtop/bottom/left/rightborders around arbitrary mid-row obstacles creates endless corner cases.Simulating the cursor step by step follows the specification directly and runs in optimal linear time: every step visits a fresh coordinate, so there are at most
m * nsteps, each checking at most 4 neighbors (<= 40,000constant-time checks on a100 x 100grid).Unify walls, obstacles, and visited cells into one helper
Notice that the cursor treats three barriers identically: stepping off
matrix, stepping onto an entry ofblocked, and stepping onto an already-visited coordinate. Combining all three checks intois_available(next_r, next_c)keeps the main loop tiny.To guarantee
O(1)time per check:- Store
DIRECTIONSin clockwise order[(0, 1), (1, 0), (0, -1), (-1, 0)], so rotating 90 degrees clockwise isdirection_idx = (direction_idx + 1) % 4. - Convert
blockedfrom[r, c]lists into asetof(r, c)tuples (listobjects are unhashable in Python, whereas tuples hash inO(1)). - Record visited coordinates in a
rows x colsboolean gridvisitedrather than a set of cell values, because distinct coordinates can contain duplicate integers.
# Clockwise direction vectors (row_delta, col_delta): right, down, left, up. DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] def spiral_with_blockers(matrix: list[list[int]], blocked: list[list[int]]) -> list[int]: rows = len(matrix) cols = len(matrix[0]) # blockers: set of (row, col) tuples so each obstacle check runs in O(1) time. blockers = set() for r, c in blocked: blockers.add((r, c)) # visited: rows x cols boolean grid tracking coordinates (cell values may repeat). visited = [] for _ in range(rows): visited.append([False] * cols) def is_available(next_r: int, next_c: int) -> bool: """Return True when (next_r, next_c) is inside the grid, unblocked, and unvisited.""" if next_r < 0 or next_r >= rows or next_c < 0 or next_c >= cols: return False if (next_r, next_c) in blockers: return False return not visited[next_r][next_c]- Store
Simulate each step with up to four clockwise rotations
Before entering the loop, place the cursor at
(0, 0)facing east (direction_idx = 0), setvisited[0][0] = True, and initializeorder = [matrix[0][0]]. Three small invariants prevent subtle bugs:- Mark
(0, 0)visited immediately. Otherwise a2 x 2walk circles back into(0, 0)and records the top-left integer twice. - Preserve
direction_idxonbreak. Breaking out of the 4-rotation search as soon asis_availablereturnsTrueleavesdirection_idxaligned with the move just made, so the next step naturally tries continuing straight ahead first. - Terminate when
next_cell is None, never by counting remaining cells. Loopingwhile len(order) < rows * cols - len(blocked):hangs forever whenever obstacles seal off unreachable open cells (as in Examples 2 and 3).
# Phase 1: Start at (0, 0) facing right (index 0) and record the starting cell immediately. r, c = 0, 0 direction_idx = 0 visited[0][0] = True order = [matrix[0][0]] # Phase 2: Repeatedly step forward, rotating 90 degrees clockwise up to 4 times if blocked. while True: next_cell = None for _ in range(4): dr, dc = DIRECTIONS[direction_idx] next_r = r + dr next_c = c + dc if is_available(next_r, next_c): # Break immediately so direction_idx stays pointed in the direction we move. next_cell = (next_r, next_c) break direction_idx = (direction_idx + 1) % 4 # Stop as soon as all 4 neighbours are unavailable (open pockets elsewhere stay unvisited). if next_cell is None: break r, c = next_cell visited[r][c] = True order.append(matrix[r][c]) return order- Mark
Walk through Example 3 visually
Trace
matrix = [[5, 10, 15], [20, 25, 30], [35, 40, 45]]withblocked = [[0, 2], [2, 0]]:Grid layout ([X] = obstacles at (0, 2) and (2, 0)): col 0 col 1 col 2 5 ---> 10 [X] | 20 25 30 (stop here!) | ^ v | [X] 40 ---> 45 coord heading clockwise checks tried action (0,0) East East:(0,1) open step East to 10 (0,1) East East:(0,2)[X] -> South:(1,1) open step South to 25 (1 turn) (1,1) South South:(2,1) open step South to 40 (2,1) South South:wall -> West:(2,0)[X] -> North:visited -> E step East to 45 (3 turns!) (2,2) East East:wall -> South:wall -> West:visited -> North step North to 30 (3 turns!) (1,2) North North:(0,2)[X] -> East:wall -> S:visited -> W:vis all 4 fail -> HALTLook closely at
(2, 1)and(2, 2): rotating 90 degrees clockwise three times in a row acts as a 90-degree left turn! A buggy implementation that tried only a single clockwise turn would stop prematurely at40. The walk returns[5, 10, 25, 40, 45, 30], leaving20at(1, 0)unvisited.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Clockwise direction vectors (row_delta, col_delta): right, down, left, up. DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] def spiral_with_blockers(matrix: list[list[int]], blocked: list[list[int]]) -> list[int]: rows = len(matrix) cols = len(matrix[0]) # blockers: set of (row, col) tuples so each obstacle check runs in O(1) time. blockers = set() for r, c in blocked: blockers.add((r, c)) # visited: rows x cols boolean grid tracking coordinates (cell values may repeat). visited = [] for _ in range(rows): visited.append([False] * cols) def is_available(next_r: int, next_c: int) -> bool: """Return True when (next_r, next_c) is inside the grid, unblocked, and unvisited.""" if next_r < 0 or next_r >= rows or next_c < 0 or next_c >= cols: return False if (next_r, next_c) in blockers: return False return not visited[next_r][next_c] # Phase 1: Start at (0, 0) facing right (index 0) and record the starting cell immediately. r, c = 0, 0 direction_idx = 0 visited[0][0] = True order = [matrix[0][0]] # Phase 2: Repeatedly step forward, rotating 90 degrees clockwise up to 4 times if blocked. while True: next_cell = None for _ in range(4): dr, dc = DIRECTIONS[direction_idx] next_r = r + dr next_c = c + dc if is_available(next_r, next_c): # Break immediately so direction_idx stays pointed in the direction we move. next_cell = (next_r, next_c) break direction_idx = (direction_idx + 1) % 4 # Stop as soon as all 4 neighbours are unavailable (open pockets elsewhere stay unvisited). if next_cell is None: break r, c = next_cell visited[r][c] = True order.append(matrix[r][c]) return order✅ Submit now — all tests should pass.
Intuition & how it works
Imagine placing a small toy robot on the top-left tile (0, 0) of a tiled floor, initially facing east (right). Ahead of the robot, three barriers look identical to its bumper sensor: a room wall, a pillar (blocked coordinate), or wet paint on a tile it has already crossed (visited coordinate). On each move, if the tile straight ahead is clear, the robot advances onto it; otherwise it pivots 90 degrees clockwise in place—testing up to all four compass headings—and steps onto the first clear tile it finds, or powers down as soon as all four surrounding tiles are blocked.
The classic spiral-matrix technique maintains four shrinking border indices (top, bottom, left, right) and peels one rectangular frame per iteration. That breaks down once obstacles appear: a single obstacle mid-row forces an early turn, bends the trajectory off a rectangle, and can seal off open tiles so the walk ends with fewer than m * n - len(blocked) items. By storing four direction vectors (pairs (dr, dc) giving the row and column offsets for east, south, west, and north), rotating with modulo arithmetic ((direction_idx + 1) % 4, wrapping 3 back around to 0), and storing obstacles in a hash set (an unordered collection supporting O(1)-average membership lookups), one compact loop treats borders, visited tiles, and obstacles uniformly.
Let's trace Example 2 (matrix = [[2, 4, 6, 8], [1, 3, 5, 7]] with obstacle [0, 2] where 6 sits):
- Start on
(0, 0)facing east: mark(0, 0)visited and record[2]. - Ahead
(0, 1)is passable -> step east to4, record[2, 4]. - Ahead
(0, 2)is inblocked-> pivot clockwise to south;(1, 1)is passable -> step south to3, record[2, 4, 3]. - Ahead
(2, 1)lies below the grid -> pivot clockwise to west;(1, 0)is passable -> step west to1, record[2, 4, 3, 1]. - From
(1, 0)facing west: west(1, -1)is off-grid, north(0, 0)is visited, east(1, 1)is visited, and south(2, 0)is off-grid—all 4 headings fail, so the robot halts with[2, 4, 3, 1], leaving8,5, and7untouched.
Complexity
Let m be the row count (len(matrix)) and n be the column count (len(matrix[0])).
- Time: O(m * n). Building the
blockersset takesO(len(blocked))time (at mostm * n - 1entries) and allocatingvisitedtakesO(m * n)time. Every iteration of thewhile Trueloop either marks a fresh coordinate visited or exits the loop, so it runs at mostm * ntimes and inspects at most 4 neighbors inO(1)time per iteration. - Space: O(m * n). The
visitedboolean grid occupiesm * nbooleans,blockersholds at mostm * n - 1coordinate tuples, andorderstores at mostm * nintegers.
Edge cases
1 x 1grid ([[7]],blocked = []):(0, 0)is recorded immediately, all four neighbors lie off-grid on the first pass, and[7]is returned.- Single row or single column: a
1 x nrow marches straight east; anm x 1column sees(0, 1)out of bounds on step 1, rotates clockwise once to south, and marches straight down. - Starting tile immediately boxed in (e.g.,
blocked = [[0, 1], [1, 0]]): all four headings from(0, 0)fail on iteration 1, cleanly returning[matrix[0][0]]. - Three clockwise rotations acting as a left turn: when straight ahead, 90 degrees right, and 180 degrees behind are all unavailable (such as
(2, 1)and(2, 2)in Example 3), rotating up to 4 times discovers the passable neighbor 270 degrees clockwise. - Stranded open pockets: unblocked tiles walled off by obstacles and visited trails (like
8, 5, 7in Example 2 and20in Example 3) are omitted without triggering an infinite loop. - Duplicate or negative integers: because
visitedtracks(r, c)coordinates rather than cell numbers, grids like[[-1, -1], [5, -10**9]]never confuse equal values at distinct coordinates.
Common mistakes
- Resetting
direction_idx = 0after every step. The cursor must maintain the heading it just stepped along; resetting to east on every step breaks even an obstacle-free spiral. - Attempting only one 90-degree rotation instead of up to four. In tight bends (such as
(2, 1)in Example 3, where south is off-grid and west is obstacle[2, 0]), a single turn fails even though east(2, 2)is open. - Ordering
DIRECTIONScounterclockwise. Confusing(row, col)with Cartesian(x, y)swaps east(0, 1)and south(1, 0), spinning the walk counterclockwise. - Forgetting
visited[0][0] = Truebefore entering the loop. Without marking(0, 0)up front, a2 x 2walk visits(0, 0) -> (0, 1) -> (1, 1) -> (1, 0)and steps back into(0, 0)a second time. - Looping
while len(order) < m * n - len(blocked):. Whenever obstacles isolate unreachable open coordinates, that count can never be reached and the loop runs forever. - Testing
[next_r, next_c] in blockeddirectly on the input list. Linearly scanningblockedon every neighbor check degrades worst-case time fromO(m * n)toO((m * n)^2).
Alternative approaches
- Four-boundary layer peel (obstacle-free case only). Track
top,bottom,left, andrightbounds to output outer rectangular rings inO(m * n)time andO(1)auxiliary space. While ideal whenblockedis guaranteed empty, it cannot handle mid-row turns or early halts around arbitrary obstacles. - In-place sentinel overwriting instead of
visited. Replacing visited entries and obstacle entries inmatrixwith a sentinel outside[-10^9, 10^9](such asNone) savesO(m * n)auxiliary space, at the cost of mutating the caller's input matrix.
Follow-up questions
-
What changes are needed if the traversal spins counterclockwise or launches from another corner of the grid? Keep the exact same simulation loop and modify only
DIRECTIONSand the initial state. For a counterclockwise spiral from(0, 0), listDIRECTIONSin counterclockwise order—south(1, 0), east(0, 1), north(-1, 0), west(0, -1)—starting atdirection_idx = 0(south). To launch clockwise from another corner such as top-right(0, cols - 1), initializer, c = 0, cols - 1withdirection_idx = 1(south), and check up front whether that starting corner itself is inblockers(returning[]if so). -
When the obstacle list is empty, how can you achieve O(1) auxiliary space while keeping the same direction-rotation logic? Without obstacles, every turn completes an entire outermost row or column, making the
visitedmatrix unnecessary. Maintain four boundstop = 0,bottom = rows - 1,left = 0,right = cols - 1; whenever stepping alongdirection_idxwould cross one of those bounds, shrink the border just completed (for exampletop += 1when rotating from east to south) and advancedirection_idx = (direction_idx + 1) % 4, halting oncetop > bottomorleft > right. -
How would you extend the function to also report every unblocked coordinate that was stranded and never visited? Once the
while Trueloop halts, iteraterover0 .. rows - 1andcover0 .. cols - 1and collect every[r, c]wherenot visited[r][c]and(r, c) not in blockers. That requires oneO(m * n)scan using the structures already in memory, and if only a boolean completeness flag is needed,len(order) == rows * cols - len(blocked)answers it inO(1)time.
Follow-up questions
- What changes are needed if the traversal spins counterclockwise or launches from another corner of the grid?
- When the obstacle list is empty, how can you achieve O(1) auxiliary space while keeping the same direction-rotation logic?
- How would you extend the function to also report every unblocked coordinate that was stranded and never visited?
Similar questions
- Longest Strictly Increasing Subsequence
- Starting Positions of Longest Uniform Substrings
- Fixed-Capacity LRU Cache
- Fewest Perfect Squares Summing to Target
- Construct Clockwise Spiral Square Matrix
- Spiral Numbering of a Square Grid
More Pinduoduo interview questions
- Starting Positions of Longest Uniform Substrings Hard
- Engineering Background, Transition Drivers, and Offer Criteria Easy
- Articulating Company Fit and Career Decision Pillars Hard Pro
- Service Scope, Data Contracts, and Cross-Team Dependencies Hard Pro
- Longest Uniform Substring Within Replacement Budget Medium Pro
- Demonstrating a Core Strength and an Active Growth Area Hard Pro
- Clockwise Spiral Grid Traversal Medium Pro
- Longest Strictly Increasing Subsequence Medium Pro
- Walking Through Your Most Challenging Engineering Project Medium Pro
- Fixed-Capacity LRU Cache Medium Pro