Furthest Unblocked Cardinal Walk Around Grid Beams

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

A rectangular arena consists of numRows rows (numbered 1 through numRows) and numColumns columns (numbered 1 through numColumns). Several beam emitters occupy coordinates listed in laserCoordinates. Every emitter at [r, c] projects two orthogonal beams that render every square in row r and every square in column c hazardous.

A rover begins at (curRow, curColumn). An overhead shield protects (curRow, curColumn) while the rover stays stationary—even if an emitter sits in curRow, in curColumn, or directly on (curRow, curColumn). However, that shield never protects any square the rover moves into (not even the very first adjacent square).

The rover picks one of the four cardinal directions—up (decreasing row), down (increasing row), left (decreasing column), or right (increasing column)—and travels in a straight line without turning. It stops immediately before leaving the arena boundaries or stepping onto a hazardous square.

Implement the function:

def longest_safe_movement(
    numRows: int,
    numColumns: int,
    curRow: int,
    curColumn: int,
    laserCoordinates: List[List[int]],
) -> int:

Return the largest number of squares the rover can safely enter along a single straight cardinal path (do not include the starting square (curRow, curColumn) in the count). If every first step is out of bounds or hazardous, return 0.

Examples

Example 1

Input:
numRows = 7
numColumns = 9
curRow = 3
curColumn = 6
laserCoordinates = [[6, 1], [7, 8]]

Output: 4

Explanation: Emitters mark rows {6, 7} and columns {1, 8} as hazardous. Starting from (3, 6): - Moving left enters (3, 5), (3, 4), (3, 3), and (3, 2) safely (4 squares) before stopping at hazardous column 1. - Moving right enters (3, 7) (1 square) before hazardous column 8. - Moving up enters (2, 6) and (1, 6) (2 squares) before the top boundary. - Moving down enters (4, 6) and (5, 6) (2 squares) before hazardous row 6. The longest safe run is 4.

Example 2

Input:
numRows = 6
numColumns = 8
curRow = 3
curColumn = 5
laserCoordinates = [[3, 2], [1, 7]]

Output: 3

Explanation: Emitter [3, 2] sweeps all of row 3, so stepping left to (3, 4) or right to (3, 6) is blocked immediately (0 squares horizontally). Column 5 has no emitter, so moving up reaches (2, 5) (1 square, stopped by hazardous row 1) and moving down reaches (4, 5), (5, 5), and (6, 5) (3 squares to the bottom edge). The maximum is 3.

Example 3

Input:
numRows = 9
numColumns = 14
curRow = 6
curColumn = 4
laserCoordinates = []

Output: 10

Explanation: With zero emitters on the arena, the rover can travel all the way to any wall: 5 squares up, 3 down, 3 left, or 10 right ((6, 5) through (6, 14)). Returning the maximum gives 10.

Constraints

  • numRows >= 1 and numColumns >= 1 (board dimensions may be very large, e.g., up to 10^9).
  • 1 <= curRow <= numRows and 1 <= curColumn <= numColumns (all coordinates are 1-indexed).
  • 0 <= len(laserCoordinates) <= 100,000
  • Every [r, c] in laserCoordinates satisfies 1 <= r <= numRows and 1 <= c <= numColumns (duplicate coordinates may occur).

Step-by-step walkthrough

  1. Understand the grid and beam rules

    We have a 1-based grid with rows 1 to numRows and columns 1 to numColumns. Every emitter at (r, c) acts like a rook in chess: it shoots a beam across all of row r and all of column c. That means any cell (row, col) on the grid is hazardous whenever:

    • row has at least one emitter anywhere in it, or
    • col has at least one emitter anywhere in it.

    The rover starts at (curRow, curColumn), picks one of the four cardinal directions (up, down, left, or right), and moves straight until the next square is either off the arena or hazardous.

    Here is Example 1 (7 x 9 arena, rover R at (3, 6), emitters E at (6, 1) and (7, 8)), where x marks hazardous squares and 4, 3, 2, 1 shows the longest safe walk leftward:

          col 1  2  3  4  5  6  7  8  9
    row 1     x  .  .  .  .  .  .  x  .
    row 2     x  .  .  .  .  .  .  x  .
    row 3     x  4  3  2  1  R  .  x  .   <- rover starts at (3, 6), walks 4 left
    row 4     x  .  .  .  .  .  .  x  .
    row 5     x  .  .  .  .  .  .  x  .
    row 6     E  x  x  x  x  x  x  x  x   <- swept by emitter (6, 1)
    row 7     x  x  x  x  x  x  x  E  x   <- swept by emitter (7, 8)
              ^                    ^
            col 1                col 8
           swept                 swept
    

    Keep two subtle rules in mind before writing any code:

    • Starting-square shielding does not travel with the rover. Even if a beam crosses (curRow, curColumn), the rover is safe while standing still, but the very first square it enters must be unblocked on its own.
    • Distant emitters still stop you. Emitter (6, 1) sits down in row 6, yet its vertical beam sweeps column 1 all the way up to row 1, stopping the rover at (3, 2) when it moves left along row 3.
  2. Why walking cell by cell can be too slow

    A straightforward simulation records all hazardous rows and columns, then steps one square at a time up, down, left, and right until hitting an edge or a hazardous square.

    That simulation is completely right on small grids, taking O(numRows + numColumns) steps after reading the L emitters. However, numRows and numColumns can be huge (up to 10^9). On a 1,000,000,000 x 1,000,000,000 grid with only 2 emitters, stepping one square at a time takes a billion iterations, whereas we can compute the exact stopping point in O(L) time using simple subtraction.

  3. Turn each axis into a 1D nearest-blocker problem

    Consider vertical movement first (walking up or down). Because the rover never changes columns, every square it enters lies in column curColumn:

    1. Is the whole column swept? If curColumn contains an emitter anywhere, then every square (r, curColumn) is hazardous. Neither up nor down can take even a single step, so both give 0.
    2. Otherwise, only emitter rows can stop the rover. Walking up toward row 1, the rover stops right before the largest hazardous row smaller than curRow (or at the top edge if none exists). Walking down toward numRows, it stops right before the smallest hazardous row greater than curRow (or at the bottom edge).

    Horizontal movement works the exact same way with rows and columns swapped: if curRow has an emitter, left and right both give 0; otherwise, only hazardous columns stop the rover.

    To avoid separate if branches for arena edges versus beams, we place sentinel values — dummy boundary coordinates just outside the valid 1..size arena — at 0 and size + 1. Look at row 3 from Example 1 (curColumn = 6, numColumns = 9, hazardous columns {1, 8}):

    col index:   0     1     2     3     4     5     6     7     8     9    10
               [wall] [x]   [.]   [.]   [.]   [.]   [R]   [.]   [x]   [.]  [wall]
                       ^                             ^           ^
                nearest_lower = 1                start = 6   nearest_higher = 8
    
    steps left  (toward 1):   6 - 1 - 1 = 4   (columns 5, 4, 3, and 2)
    steps right (toward 9):   8 - 6 - 1 = 1   (column 7)
    

    In general, the number of whole numbers strictly between a and b (with a < b) is always b - a - 1, because we exclude both endpoints.

  4. Write the 1D helper function

    Let's turn that number-line picture into count_safe_steps_along_axis. It scans the set of blocked lines once and tracks the closest blocker below start_pos and the closest blocker above start_pos.

    Notice why the comparisons nearest_lower_blocker < line < start_pos and start_pos < line < nearest_higher_blocker use strict <: if line == start_pos (for example, an emitter sits in row curRow as in Example 2), that emitter sweeps curRow horizontally, not the rows above or below (curRow, curColumn) when stepping vertically.

    from typing import Set, Tuple
    
    
    def count_safe_steps_along_axis(
        start_pos: int, board_limit: int, blocked_lines: Set[int]
    ) -> Tuple[int, int]:
        """Count safe cells from start_pos toward 1 and toward board_limit."""
        # Sentinel walls sit just outside the valid 1..board_limit coordinates.
        nearest_lower_blocker = 0
        nearest_higher_blocker = board_limit + 1
    
        # Find the closest blocked row/column on each side of start_pos.
        for line in blocked_lines:
            # Strictly less than start_pos: stops movement toward index 1.
            # Note: line == start_pos is ignored here because moving perpendicular
            # to start_pos steps immediately off start_pos onto adjacent indices.
            if nearest_lower_blocker < line < start_pos:
                nearest_lower_blocker = line
            # Strictly greater than start_pos: stops movement toward board_limit.
            elif start_pos < line < nearest_higher_blocker:
                nearest_higher_blocker = line
    
        # Subtract 1 because neither start_pos nor the blocking line itself is counted.
        steps_toward_start = start_pos - nearest_lower_blocker - 1
        steps_toward_end = nearest_higher_blocker - start_pos - 1
        return steps_toward_start, steps_toward_end
    
  5. Combine all four directions

    Now we gather the emitter rows and emitter columns into two hash sets (unordered collections that automatically discard duplicates and answer "is X in this set?" in constant O(1) time):

    • If curColumn is not in laser_columns, vertical moves are allowed, and laser_rows act as the blockers along 1..numRows.
    • If curRow is not in laser_rows, horizontal moves are allowed, and laser_columns act as the blockers along 1..numColumns.

    Initializing best_steps = 0 automatically handles the case where every direction is blocked.

    def longest_safe_movement(
        numRows: int,
        numColumns: int,
        curRow: int,
        curColumn: int,
        laserCoordinates: List[List[int]],
    ) -> int:
        # laser_rows: set of 1-based row indices destroyed by lasers, e.g. {6, 7}
        laser_rows: Set[int] = set()
        # laser_columns: set of 1-based column indices destroyed by lasers, e.g. {1, 8}
        laser_columns: Set[int] = set()
    
        # Phase 1: Collect every row and column covered by at least one laser.
        for row, column in laserCoordinates:
            laser_rows.add(row)
            laser_columns.add(column)
    
        best_steps = 0
    
        # Phase 2: Check vertical movement (up and down stay inside curColumn).
        # If curColumn contains any laser, every destination cell in curColumn is destroyed.
        if curColumn not in laser_columns:
            steps_up, steps_down = count_safe_steps_along_axis(
                curRow, numRows, laser_rows
            )
            best_steps = max(best_steps, steps_up, steps_down)
    
        # Phase 3: Check horizontal movement (left and right stay inside curRow).
        # If curRow contains any laser, every destination cell in curRow is destroyed.
        if curRow not in laser_rows:
            steps_left, steps_right = count_safe_steps_along_axis(
                curColumn, numColumns, laser_columns
            )
            best_steps = max(best_steps, steps_left, steps_right)
    
        return best_steps
    
  6. Trace Example 1 and Example 2

    Let's verify both open-lane blocking and same-row blocking:

    Example 1: 7 x 9 arena, start (3, 6), emitters [[6, 1], [7, 8]]
      laser_rows = {6, 7}, laser_columns = {1, 8}
      Vertical (col 6 not in {1, 8}):
        nearest_lower = 0, nearest_higher = 6 -> up = 3 - 0 - 1 = 2, down = 6 - 3 - 1 = 2
      Horizontal (row 3 not in {6, 7}):
        nearest_lower = 1, nearest_higher = 8 -> left = 6 - 1 - 1 = 4, right = 8 - 6 - 1 = 1
      best_steps = max(0, 2, 2, 4, 1) = 4
    
    Example 2: 6 x 8 arena, start (3, 5), emitters [[3, 2], [1, 7]]
      laser_rows = {1, 3}, laser_columns = {2, 7}
      Vertical (col 5 not in {2, 7}):
        line 3 == start_pos 3 is ignored -> nearest_lower = 1, nearest_higher = 7
        up = 3 - 1 - 1 = 1 (row 2), down = 7 - 3 - 1 = 3 (rows 4, 5, 6)
      Horizontal (row 3 IS in {1, 3}):
        skipped! Every square in row 3 is swept, so left and right give 0.
      best_steps = 3
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_safe_steps_along_axis(
        start_pos: int, board_limit: int, blocked_lines: Set[int]
    ) -> Tuple[int, int]:
        """Count safe cells from start_pos toward 1 and toward board_limit."""
        # Sentinel walls sit just outside the valid 1..board_limit coordinates.
        nearest_lower_blocker = 0
        nearest_higher_blocker = board_limit + 1
    
        # Find the closest blocked row/column on each side of start_pos.
        for line in blocked_lines:
            # Strictly less than start_pos: stops movement toward index 1.
            # Note: line == start_pos is ignored here because moving perpendicular
            # to start_pos steps immediately off start_pos onto adjacent indices.
            if nearest_lower_blocker < line < start_pos:
                nearest_lower_blocker = line
            # Strictly greater than start_pos: stops movement toward board_limit.
            elif start_pos < line < nearest_higher_blocker:
                nearest_higher_blocker = line
    
        # Subtract 1 because neither start_pos nor the blocking line itself is counted.
        steps_toward_start = start_pos - nearest_lower_blocker - 1
        steps_toward_end = nearest_higher_blocker - start_pos - 1
        return steps_toward_start, steps_toward_end
    
    
    def longest_safe_movement(
        numRows: int,
        numColumns: int,
        curRow: int,
        curColumn: int,
        laserCoordinates: List[List[int]],
    ) -> int:
        # laser_rows: set of 1-based row indices destroyed by lasers, e.g. {6, 7}
        laser_rows: Set[int] = set()
        # laser_columns: set of 1-based column indices destroyed by lasers, e.g. {1, 8}
        laser_columns: Set[int] = set()
    
        # Phase 1: Collect every row and column covered by at least one laser.
        for row, column in laserCoordinates:
            laser_rows.add(row)
            laser_columns.add(column)
    
        best_steps = 0
    
        # Phase 2: Check vertical movement (up and down stay inside curColumn).
        # If curColumn contains any laser, every destination cell in curColumn is destroyed.
        if curColumn not in laser_columns:
            steps_up, steps_down = count_safe_steps_along_axis(
                curRow, numRows, laser_rows
            )
            best_steps = max(best_steps, steps_up, steps_down)
    
        # Phase 3: Check horizontal movement (left and right stay inside curRow).
        # If curRow contains any laser, every destination cell in curRow is destroyed.
        if curRow not in laser_rows:
            steps_left, steps_right = count_safe_steps_along_axis(
                curColumn, numColumns, laser_columns
            )
            best_steps = max(best_steps, steps_left, steps_right)
    
        return best_steps
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture standing at a hallway intersection inside a grid-shaped warehouse where every laser turret acts like a rook in chess, firing one continuous beam across its entire row and another across its entire column. When you pick one direction and walk in a straight line, only two things can stop you: either the hallway you are walking down already has a beam running straight along it (making zero steps possible), or you keep walking until you hit the closest cross-beam or the outer wall.

The naive approach builds a numRows x numColumns 2D grid, marks every destroyed cell, and walks outward one square at a time. That wastes O(numRows * numColumns) memory and O(numRows + numColumns) time, which will run out of memory or time out if the board is huge (say 10^9 x 10^9) with only a few lasers. Instead, we store just the row numbers and column numbers of the lasers in two hash sets (unordered collections with O(1) membership lookup) and find the nearest blocking line in each direction using sentinel values (dummy wall coordinates at 0 and size + 1 placed just outside the 1..size board so edges use the same subtraction formula as laser beams).

Walk through Example 1 (7 x 9 arena, rover at (3, 6), emitters at (6, 1) and (7, 8)):

  1. Emitters sweep rows {6, 7} (laser_rows = {6, 7}) and columns {1, 8} (laser_columns = {1, 8}).
  2. Vertical moves (along column 6): Column 6 is not in {1, 8}, so it is open. Moving up from row 3 hits sentinel wall 0 (3 - 0 - 1 = 2 squares), and moving down hits hazardous row 6 (6 - 3 - 1 = 2 squares).
  3. Horizontal moves (along row 3): Row 3 is not in {6, 7}, so it is open. Moving left from column 6 hits hazardous column 1 (6 - 1 - 1 = 4 squares: (3, 5) down to (3, 2)), and moving right hits hazardous column 8 (8 - 6 - 1 = 1 square).
  4. The longest safe run across all four directions is max(2, 2, 4, 1) = 4.

Complexity

Let L be the number of coordinates in laserCoordinates.

  • Time: O(L). We loop over the L lasers once to populate laser_rows and laser_columns, then scan laser_rows (at most L entries) once for vertical moves and laser_columns (at most L entries) once for horizontal moves. Because numRows and numColumns only appear in constant-time arithmetic, a 10^9 x 10^9 board runs just as fast as an 8 x 8 board.
  • Space: O(L). The two hash sets store at most L distinct row indices and L distinct column indices, using memory proportional only to the number of lasers.

Edge cases

  • No emitters (laserCoordinates = []): Both sets are empty, so every direction walks all the way to its sentinel wall, returning max(curRow - 1, numRows - curRow, curColumn - 1, numColumns - curColumn).
  • Emitter directly on (curRow, curColumn): Both curRow and curColumn are added to the blocked sets, so both if checks are skipped and the function returns 0 (standing on the start is shielded, stepping anywhere else is not).
  • Emitter elsewhere in curRow or curColumn: In Example 2, [3, 2] when starting at (3, 5) sweeps all of row 3 (blocking left and right) while still allowing vertical steps out of row 3 into row 2 or rows 4..6.
  • Emitter immediately adjacent to the start: If nearest_lower_blocker == curRow - 1, the formula curRow - (curRow - 1) - 1 cleanly evaluates to 0.
  • 1 x 1 or single-row/single-column arenas: On a 1 x 1 arena, 1 - 0 - 1 = 0 and 2 - 1 - 1 = 0, returning 0 with no special-case code.
  • Duplicate emitters or multiple emitters in the same row: Hash sets collapse duplicates automatically, and the scan keeps only the closest blocking line on each side.

Common mistakes

  • Treating each emitter as a single blocked square. An emitter at (6, 1) sweeps all of row 6 and all of column 1, so a rover walking left along row 3 is still stopped at column 1.
  • Extending starting-square shielding to the rover's row or column. Shielding applies strictly to remaining at (curRow, curColumn); if an emitter sits anywhere in curRow, moving left or right enters an unshielded, hazardous square immediately.
  • Off-by-one errors at arena boundaries. Because coordinates are 1-based (1 through size), placing virtual walls at 0 and size + 1 ensures blocker - start_pos - 1 counts neither the starting square nor the wall/beam itself.
  • Letting line == start_pos overwrite a perpendicular blocker. When moving vertically out of curRow, an emitter in curRow lies behind you at step zero, not ahead of you, so strict < comparisons are essential.
  • Allocating a full numRows x numColumns boolean matrix. Materializing the grid wastes massive memory and time whenever dimensions are large and emitters are sparse.

Follow-up questions

  • How would you answer K independent starting-position queries against the same static list of L emitters? Sort the unique laser_rows and laser_columns once in O(L log L) preprocessing time while keeping the two hash sets for O(1) same-row and same-column checks. Then each query can use binary search (repeatedly halving a sorted array to locate a target boundary in logarithmic time) via bisect_left and bisect_right to find nearest_lower_blocker and nearest_higher_blocker in O(log L) time per query instead of O(L).
  • What changes if each emitter blocks only its own grid square (r, c) rather than sweeping an entire row and column? Then an obstacle can only block vertical movement if its column equals curColumn, and can only block horizontal movement if its row equals curRow. Filter laserCoordinates into same_col_rows (rows of obstacles in curColumn) and same_row_cols (columns of obstacles in curRow), remove the whole-lane not in checks (keeping only r != curRow and c != curColumn via strict <), and pass those filtered sets into the exact same count_safe_steps_along_axis helper.
  • Can a single query be answered in O(1) auxiliary memory without building row and column hash sets? Yes: in one pass over laserCoordinates, track two booleans (row_swept when r == curRow and col_swept when c == curColumn) along with four integers (nearest_row_above, nearest_row_below, nearest_col_left, nearest_col_right). That preserves O(L) time while shrinking auxiliary memory from O(L) down to six scalar variables.

Follow-up questions

Similar questions

More Roblox interview questions

All 84 Roblox questions →