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 when 0 <= r < m, 0 <= c < n, [r, c] is absent from blocked, and (r, c) has not yet been visited.
  • Starting position: Navigation begins at (0, 0) oriented east. Coordinate (0, 0) is immediately marked visited and matrix[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, where m = len(matrix) and n = len(matrix[0]) (every row has length n).
  • -10^9 <= matrix[r][c] <= 10^9
  • 0 <= len(blocked) <= m * n - 1
  • All [r, c] pairs in blocked are distinct valid coordinates inside matrix, and [0, 0] never appears in blocked.

Step-by-step walkthrough

  1. Understand the cursor's rules

    We receive an m x n integer grid matrix and a list of obstacle coordinates blocked = [[r, c], ...]. Starting on (0, 0) facing east (right), our cursor advances one cell at a time by repeating one decision loop:

    1. Inspect the neighbor directly ahead along the current heading.
    2. 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.
    3. Otherwise, rotate 90 degrees clockwise in place and inspect again—testing up to all 4 cardinal headings from the current coordinate.
    4. 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 -> East
    

    When blocked is empty, encountering grid borders and previously visited outer rings automatically guides the cursor through the standard inward spiral.

  2. 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 column 1, followed by a westward step into 1, where the cursor gets boxed in—leaving 8, 5, and 7 stranded on the right half of the grid. Trying to patch top/bottom/left/right borders 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 * n steps, each checking at most 4 neighbors (<= 40,000 constant-time checks on a 100 x 100 grid).

  3. Unify walls, obstacles, and visited cells into one helper

    Notice that the cursor treats three barriers identically: stepping off matrix, stepping onto an entry of blocked, and stepping onto an already-visited coordinate. Combining all three checks into is_available(next_r, next_c) keeps the main loop tiny.

    To guarantee O(1) time per check:

    • Store DIRECTIONS in clockwise order [(0, 1), (1, 0), (0, -1), (-1, 0)], so rotating 90 degrees clockwise is direction_idx = (direction_idx + 1) % 4.
    • Convert blocked from [r, c] lists into a set of (r, c) tuples (list objects are unhashable in Python, whereas tuples hash in O(1)).
    • Record visited coordinates in a rows x cols boolean grid visited rather 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]
    
  4. Simulate each step with up to four clockwise rotations

    Before entering the loop, place the cursor at (0, 0) facing east (direction_idx = 0), set visited[0][0] = True, and initialize order = [matrix[0][0]]. Three small invariants prevent subtle bugs:

    1. Mark (0, 0) visited immediately. Otherwise a 2 x 2 walk circles back into (0, 0) and records the top-left integer twice.
    2. Preserve direction_idx on break. Breaking out of the 4-rotation search as soon as is_available returns True leaves direction_idx aligned with the move just made, so the next step naturally tries continuing straight ahead first.
    3. Terminate when next_cell is None, never by counting remaining cells. Looping while 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
    
  5. Walk through Example 3 visually

    Trace matrix = [[5, 10, 15], [20, 25, 30], [35, 40, 45]] with blocked = [[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 -> HALT
    

    Look 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 at 40. The walk returns [5, 10, 25, 40, 45, 30], leaving 20 at (1, 0) unvisited.

  6. 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):

  1. Start on (0, 0) facing east: mark (0, 0) visited and record [2].
  2. Ahead (0, 1) is passable -> step east to 4, record [2, 4].
  3. Ahead (0, 2) is in blocked -> pivot clockwise to south; (1, 1) is passable -> step south to 3, record [2, 4, 3].
  4. Ahead (2, 1) lies below the grid -> pivot clockwise to west; (1, 0) is passable -> step west to 1, record [2, 4, 3, 1].
  5. 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], leaving 8, 5, and 7 untouched.

Complexity

Let m be the row count (len(matrix)) and n be the column count (len(matrix[0])).

  • Time: O(m * n). Building the blockers set takes O(len(blocked)) time (at most m * n - 1 entries) and allocating visited takes O(m * n) time. Every iteration of the while True loop either marks a fresh coordinate visited or exits the loop, so it runs at most m * n times and inspects at most 4 neighbors in O(1) time per iteration.
  • Space: O(m * n). The visited boolean grid occupies m * n booleans, blockers holds at most m * n - 1 coordinate tuples, and order stores at most m * n integers.

Edge cases

  • 1 x 1 grid ([[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 n row marches straight east; an m x 1 column 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, 7 in Example 2 and 20 in Example 3) are omitted without triggering an infinite loop.
  • Duplicate or negative integers: because visited tracks (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 = 0 after 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 DIRECTIONS counterclockwise. Confusing (row, col) with Cartesian (x, y) swaps east (0, 1) and south (1, 0), spinning the walk counterclockwise.
  • Forgetting visited[0][0] = True before entering the loop. Without marking (0, 0) up front, a 2 x 2 walk 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 blocked directly on the input list. Linearly scanning blocked on every neighbor check degrades worst-case time from O(m * n) to O((m * n)^2).

Alternative approaches

  • Four-boundary layer peel (obstacle-free case only). Track top, bottom, left, and right bounds to output outer rectangular rings in O(m * n) time and O(1) auxiliary space. While ideal when blocked is 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 in matrix with a sentinel outside [-10^9, 10^9] (such as None) saves O(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 DIRECTIONS and the initial state. For a counterclockwise spiral from (0, 0), list DIRECTIONS in counterclockwise order—south (1, 0), east (0, 1), north (-1, 0), west (0, -1)—starting at direction_idx = 0 (south). To launch clockwise from another corner such as top-right (0, cols - 1), initialize r, c = 0, cols - 1 with direction_idx = 1 (south), and check up front whether that starting corner itself is in blockers (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 visited matrix unnecessary. Maintain four bounds top = 0, bottom = rows - 1, left = 0, right = cols - 1; whenever stepping along direction_idx would cross one of those bounds, shrink the border just completed (for example top += 1 when rotating from east to south) and advance direction_idx = (direction_idx + 1) % 4, halting once top > bottom or left > right.

  • How would you extend the function to also report every unblocked coordinate that was stranded and never visited? Once the while True loop halts, iterate r over 0 .. rows - 1 and c over 0 .. cols - 1 and collect every [r, c] where not visited[r][c] and (r, c) not in blockers. That requires one O(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 in O(1) time.

Follow-up questions

Similar questions

More Pinduoduo interview questions

All 17 Pinduoduo questions →