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 >= 1andnumColumns >= 1(board dimensions may be very large, e.g., up to10^9).1 <= curRow <= numRowsand1 <= curColumn <= numColumns(all coordinates are 1-indexed).0 <= len(laserCoordinates) <= 100,000- Every
[r, c]inlaserCoordinatessatisfies1 <= r <= numRowsand1 <= c <= numColumns(duplicate coordinates may occur).
Step-by-step walkthrough
Understand the grid and beam rules
We have a 1-based grid with rows
1tonumRowsand columns1tonumColumns. Every emitter at(r, c)acts like a rook in chess: it shoots a beam across all of rowrand all of columnc. That means any cell(row, col)on the grid is hazardous whenever:rowhas at least one emitter anywhere in it, orcolhas 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 9arena, roverRat(3, 6), emittersEat(6, 1)and(7, 8)), wherexmarks hazardous squares and4, 3, 2, 1shows 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 sweptKeep 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 row6, yet its vertical beam sweeps column1all the way up to row1, stopping the rover at(3, 2)when it moves left along row3.
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 theLemitters. However,numRowsandnumColumnscan be huge (up to10^9). On a1,000,000,000 x 1,000,000,000grid with only2emitters, stepping one square at a time takes a billion iterations, whereas we can compute the exact stopping point inO(L)time using simple subtraction.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:- Is the whole column swept? If
curColumncontains an emitter anywhere, then every square(r, curColumn)is hazardous. Neither up nor down can take even a single step, so both give0. - Otherwise, only emitter rows can stop the rover. Walking up toward row
1, the rover stops right before the largest hazardous row smaller thancurRow(or at the top edge if none exists). Walking down towardnumRows, it stops right before the smallest hazardous row greater thancurRow(or at the bottom edge).
Horizontal movement works the exact same way with rows and columns swapped: if
curRowhas an emitter, left and right both give0; otherwise, only hazardous columns stop the rover.To avoid separate
ifbranches for arena edges versus beams, we place sentinel values — dummy boundary coordinates just outside the valid1..sizearena — at0andsize + 1. Look at row3from 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
aandb(witha < b) is alwaysb - a - 1, because we exclude both endpoints.- Is the whole column swept? If
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 belowstart_posand the closest blocker abovestart_pos.Notice why the comparisons
nearest_lower_blocker < line < start_posandstart_pos < line < nearest_higher_blockeruse strict<: ifline == start_pos(for example, an emitter sits in rowcurRowas in Example 2), that emitter sweepscurRowhorizontally, 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_endCombine 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 constantO(1)time):- If
curColumnis not inlaser_columns, vertical moves are allowed, andlaser_rowsact as the blockers along1..numRows. - If
curRowis not inlaser_rows, horizontal moves are allowed, andlaser_columnsact as the blockers along1..numColumns.
Initializing
best_steps = 0automatically 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- If
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 = 3Complete 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)):
- Emitters sweep rows
{6, 7}(laser_rows = {6, 7}) and columns{1, 8}(laser_columns = {1, 8}). - Vertical moves (along column
6): Column6is not in{1, 8}, so it is open. Moving up from row3hits sentinel wall0(3 - 0 - 1 = 2squares), and moving down hits hazardous row6(6 - 3 - 1 = 2squares). - Horizontal moves (along row
3): Row3is not in{6, 7}, so it is open. Moving left from column6hits hazardous column1(6 - 1 - 1 = 4squares:(3, 5)down to(3, 2)), and moving right hits hazardous column8(8 - 6 - 1 = 1square). - 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 theLlasers once to populatelaser_rowsandlaser_columns, then scanlaser_rows(at mostLentries) once for vertical moves andlaser_columns(at mostLentries) once for horizontal moves. BecausenumRowsandnumColumnsonly appear in constant-time arithmetic, a10^9 x 10^9board runs just as fast as an8 x 8board. - Space:
O(L). The two hash sets store at mostLdistinct row indices andLdistinct 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, returningmax(curRow - 1, numRows - curRow, curColumn - 1, numColumns - curColumn). - Emitter directly on
(curRow, curColumn): BothcurRowandcurColumnare added to the blocked sets, so bothifchecks are skipped and the function returns0(standing on the start is shielded, stepping anywhere else is not). - Emitter elsewhere in
curRoworcurColumn: In Example 2,[3, 2]when starting at(3, 5)sweeps all of row3(blocking left and right) while still allowing vertical steps out of row3into row2or rows4..6. - Emitter immediately adjacent to the start: If
nearest_lower_blocker == curRow - 1, the formulacurRow - (curRow - 1) - 1cleanly evaluates to0. 1 x 1or single-row/single-column arenas: On a1 x 1arena,1 - 0 - 1 = 0and2 - 1 - 1 = 0, returning0with 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 row6and all of column1, so a rover walking left along row3is still stopped at column1. - Extending starting-square shielding to the rover's row or column. Shielding applies strictly to remaining at
(curRow, curColumn); if an emitter sits anywhere incurRow, moving left or right enters an unshielded, hazardous square immediately. - Off-by-one errors at arena boundaries. Because coordinates are 1-based (
1throughsize), placing virtual walls at0andsize + 1ensuresblocker - start_pos - 1counts neither the starting square nor the wall/beam itself. - Letting
line == start_posoverwrite a perpendicular blocker. When moving vertically out ofcurRow, an emitter incurRowlies behind you at step zero, not ahead of you, so strict<comparisons are essential. - Allocating a full
numRows x numColumnsboolean 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_rowsandlaser_columnsonce inO(L log L)preprocessing time while keeping the two hash sets forO(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) viabisect_leftandbisect_rightto findnearest_lower_blockerandnearest_higher_blockerinO(log L)time per query instead ofO(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 equalscurRow. FilterlaserCoordinatesintosame_col_rows(rows of obstacles incurColumn) andsame_row_cols(columns of obstacles incurRow), remove the whole-lanenot inchecks (keeping onlyr != curRowandc != curColumnvia strict<), and pass those filtered sets into the exact samecount_safe_steps_along_axishelper. - 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_sweptwhenr == curRowandcol_sweptwhenc == curColumn) along with four integers (nearest_row_above,nearest_row_below,nearest_col_left,nearest_col_right). That preservesO(L)time while shrinking auxiliary memory fromO(L)down to six scalar variables.
Follow-up questions
- How would you answer K independent starting-position queries against the same static list of L emitters?
- What changes if each emitter blocks only its own grid square (r, c) rather than sweeping an entire row and column?
- Can a single query be answered in O(1) auxiliary memory without building row and column hash sets?
Similar questions
- Valid Hat Pairings and Maximum Score
- Centered Span Availability Queries Over Dynamic Reservations
- Robot Trajectory Boundedness with Obstacles
- Grid Robot Return to Origin
- Grid Streak Removal and Column Gravity
- Per-Client Sliding Window Hit Counter
More Roblox interview questions
- Detect Grid Streaks and Collapse Columns Medium
- Grid Streak Removal and Column Gravity Medium
- Dual-Key Sliding Window Request Throttler Medium Pro
- Profit-Optimal Three-Stage Bakery Line Medium Pro
- Bayesian Posterior and Marginal Evidence Hard Pro
- Per-Group Top-k Semantics: ROW_NUMBER, RANK, and DENSE_RANK Medium Pro
- Difference-in-Differences Effect and Pretrend Check Hard Pro
- Total Sample Size Calculator for Two-Arm Z-Tests Hard Pro
- Per-Arm Power Sizing and Bayesian Posterior Updating Hard Pro
- Valid Hat Pairings and Maximum Score Hard Pro