Longest safe straight move for a robot between lasers
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Databricks's online assessment, last asked Aug 2024. It tests matrix, simulation and hash sets.
A board has num_rows × num_columns cells and some lasers. Each laser sits on a cell and destroys every cell in its row and its column. A robot stands on a given cell; its own cell is safe even if a beam crosses it. The robot picks one of the four directions and moves straight until it reaches the edge of the board or the next cell is destroyed. Return the largest number of cells it can move into, over the four directions.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
max_moves(num_rows: int, num_columns: int, cur_row: int, cur_column: int, lasers: list[list[int]]) -> int— coordinates are 1-based; each laser is[row, column].
Example
max_moves(8, 8, 5, 3, [[1, 6], [2, 8]]) -> 3
# rows 1 and 2 and columns 6 and 8 are destroyed
# down: (6,3), (7,3), (8,3) = 3; up: (4,3), (3,3) = 2; right: (5,4), (5,5) = 2; left: (5,2), (5,1) = 2
Constraints
- Coordinates are 1-based, and the robot and every laser are on the board.
Clarifying questions
- Are coordinates 1-based?
- Does a laser's beam stop at another laser, or cross the whole board?
- Can the robot pass through a destroyed cell (no)?
What a strong answer covers
- Sets of destroyed rows and columns.
- Moving vertically only crosses rows (the column stays the robot's own), so the distance up is the gap to the nearest destroyed row above (or the edge), and likewise for the other three directions.
- For a very large board: sorted lists of destroyed rows and columns plus binary search, O(L log L) to build and O(log L) per direction, independent of the board size.
- Edge cases: the robot on the edge of the board; a laser in the robot's own row, which leaves 0 moves left and right (every other cell of that row is destroyed).
- Tests for each.
Follow-ups
- Answer many robot positions on the same board.
- Lasers only fire in one direction from their cell.
- The robot may turn once. What is the longest path now?
Where it's asked
- Databricks · Online assessment · Last asked Aug 2024Timed online coding test
What it tests
matrix · simulation · hash sets
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
