Simulating a Marble on a Timed Tilting Grid
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A single marble sits inside a rectangular grid maze made up of open floor tiles ('.') and solid walls ('#'). Cell positions use 0-indexed [row, col] coordinates, where row = 0 is the top row and col = 0 is the leftmost column.
def ball_position(maze: list[str], start: list[int], events: list[tuple[int, str]], end_time: int) -> list[int]:
You are given maze, the marble's initial cell start, a chronological list events of (t, state) pairs that change the grid's inclination, and an integer end_time. Determine which cell [row, col] the marble occupies at timestamp end_time under the following rules:
- Starting at timestamp
0(prior to the earliest event), the grid inclination is"flat". - Each event
(t, state)sets the grid inclination tostatestarting at timestampt, and that inclination remains active until the next event. Valid inclinations are"up","down","left","right", and"flat". - Simulation runs across discrete 1-second intervals
s = 0, 1, ..., end_time - 1. During seconds, the active inclination is thestateset by the latest event satisfyingt <= s(or"flat"if none exists). - When the inclination during second
sis"flat", the marble stays still. Otherwise, it attempts to step one cell in the active direction:"up"moves(row, col)toward(row - 1, col)"down"moves(row, col)toward(row + 1, col)"left"moves(row, col)toward(row, col - 1)"right"moves(row, col)toward(row, col + 1)
- If that neighboring coordinate lies strictly inside the grid bounds and contains
'.', the marble rolls into it by the end of seconds; if the neighbor is out of bounds or contains'#', the marble remains in its current cell. - Any event with
t >= end_timefires at or after termination and has no effect. Ifend_time == 0, zero seconds elapse and the marble stays atstart.
Examples
Example 1
Input:
maze = ["######", "#....#", "#.##.#", "#....#", "######"]
start = [3, 1]
events = [(0, "right"), (2, "up"), (4, "flat"), (7, "right")]
end_time = 10
Output:
[3, 4]
Walk-through:
- Seconds 0 and 1 ("right") roll the marble from (3, 1) through (3, 2) to (3, 3).
- Seconds 2 and 3 ("up") try to enter (2, 3), which is '#', so the marble remains at (3, 3).
- Seconds 4 through 6 ("flat") keep the grid level with no movement.
- Second 7 ("right") advances the marble to (3, 4), and the wall at (3, 5) blocks any further movement during seconds 8 and 9.
Example 2
Input:
maze = [".....", ".###.", "....."]
start = [0, 0]
events = [(2, "right"), (50, "down"), (52, "left")]
end_time = 54
Output:
[2, 2]
Walk-through:
- Seconds 0 and 1 occur before the first event, so the grid stays "flat" and the marble waits at (0, 0).
- Seconds 2 through 49 ("right", 48 seconds) move 4 steps to (0, 4) and then stop against the right grid border for the remaining 44 seconds.
- Seconds 50 and 51 ("down") roll two rows down the right column to (2, 4).
- Seconds 52 and 53 ("left") roll two columns left to (2, 2), where the simulation ends at end_time = 54.
Example 3
Input:
maze = ["...", "..."]
start = [0, 1]
events = [(0, "up"), (1, "left"), (3, "down"), (4, "right")]
end_time = 4
Output:
[1, 0]
Walk-through:
- Second 0 ("up") is blocked by the top grid edge at (0, 1).
- Seconds 1 and 2 ("left") step to (0, 0) on second 1 and wait against the left edge on second 2.
- Second 3 ("down") steps to (1, 0).
- Event (4, "right") occurs at t == end_time, so it never takes effect.
Constraints
1 <= len(maze) <= 100and1 <= len(maze[0]) <= 100; all strings inmazeshare equal length and contain only'.'or'#'.start == [row, col]points to an open cell (maze[row][col] == '.').0 <= len(events) <= 10^4- For every
(t, state)inevents,0 <= t <= 10^9, timestampstare strictly increasing, andstateis in{"up", "down", "left", "right", "flat"}. 0 <= end_time <= 10^9
Step-by-step walkthrough
Understand the grid and timing rules
We are given a rectangular grid
mazeof'#'(wall) and'.'(open cell), a starting positionstart = [row, col], a list of strictly increasing(time, state)events, and an integerend_time.Let's pin down the exact movement and timing rules:
Grid coordinates (row 0 = top, col 0 = left): "up" (-1, 0) ^ | "left" (0, -1) <-+-> "right" (0, +1) | v "down" (+1, 0)- Simulated seconds: Only whole seconds
s = 0, 1, ..., end_time - 1happen. Ifend_time == 0, zero seconds pass and the ball stays atstart. Any event withtime >= end_timehas no effect. - Board state: Before the first event, the board is
"flat"(the ball never moves). An event(t, state)sets the board tostatestarting at secondtuntil the next event. - Rolling and walls: During each tilted second, the ball moves
1cell in that direction if the target cell is inside the grid and'.'. Grid boundaries act just like'#'walls.
- Simulated seconds: Only whole seconds
Why second-by-second simulation is too slow
The most direct translation of the rules loops
for s in range(end_time):, looks up the active tilt state, and tries to move one step. That logic is easy to trust (and makes a great test oracle for small inputs), butend_timecan be as large as10^9—a billion loop iterations will time out in Python.Why is that loop wasting so much work? Suppose the maze is
100 × 100and an event tilts the board"left"for900,000,000seconds. Within at most99seconds, the ball rolls into a wall or the left border of the grid—and for the remaining899,999,901seconds it just sits pressed against that wall doing nothing!Key idea: group time into constant-tilt intervals
Instead of stepping one second at a time, split the timeline at the event timestamps. Between two consecutive events, the tilt direction never changes:
Timeline from 0 to end_time: 0 t0 t1 t2 end_time |----------|-------------|----------------|--------------| "flat" events[0] events[1] events[2] (skip!) (t1 - t0 sec) (t2 - t1 sec) (end_time - t2 sec)Look at what happens inside a single interval of length
remaining_seconds:- Before
events[0], the board is"flat", so the ball stays atstart—we can skip[0, t0)completely. - If an interval's state is
"flat", nothing moves—skip the whole interval inO(1)time. - If an interval tilts in direction
(dr, dc), the ball rolls straight ahead one cell per second until eitherremaining_secondshits0or the next cell is a wall / out of bounds. Once blocked, it stays blocked for the rest of that interval!
Because the maze is at most
100 × 100, a straight-line roll can take at most99steps before hitting a wall or grid border. Even with10^4events andend_time = 10^9, the total number of single-cell steps across the entire run is at most10^4 × 99 < 10^6.- Before
Check grid bounds safely
Before moving into
(next_row, next_col), we need a helperis_open_cell. In Python, negative list indices likemaze[-1]silently wrap around to the last row instead of raising an error! Checkingrow < 0andcol < 0explicitly ensures every edge of the grid acts like a solid wall.DIRECTIONS: Dict[str, Tuple[int, int]] = { "up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1), } def is_open_cell(maze: list[str], row: int, col: int) -> bool: """Return True if (row, col) lies inside the maze bounds and is not a '#' wall.""" if row < 0 or row >= len(maze) or col < 0 or col >= len(maze[0]): return False return maze[row][col] == "."Slice each event interval and roll until blocked
For event
istarting atinterval_start = events[i][0]:- Early exit (
interval_start >= end_time): Because event times are strictly increasing and only seconds0 .. end_time - 1count, an event atend_timeor later never takes effect, so webreak. - Clamp the end (
interval_end): The tilt lasts until the next eventevents[i + 1][0], orend_timeif there is no next event (or if the next event happens afterend_time). Clamping toend_timeprevents the last active tilt from rolling the ball past the end of the simulation. - Bounded
whileroll:while remaining_seconds > 0 and is_open_cell(maze, row + dr, col + dc):advances one cell at a time and exits immediately as soon as a wall or border blocks the ball.
def ball_position(maze: list[str], start: list[int], events: list[tuple[int, str]], end_time: int) -> list[int]: row, col = start[0], start[1] num_events = len(events) for i in range(num_events): interval_start, state = events[i][0], events[i][1] if interval_start >= end_time: break interval_end = end_time if i + 1 < num_events and events[i + 1][0] < end_time: interval_end = events[i + 1][0] remaining_seconds = interval_end - interval_start if state == "flat": continue dr, dc = DIRECTIONS[state] while remaining_seconds > 0 and is_open_cell(maze, row + dr, col + dc): row += dr col += dc remaining_seconds -= 1 return [row, col]- Early exit (
Trace Example 2 step by step
Let's trace Example 2 (
maze = [".....", ".###.", "....."],start = [0, 0],events = [(2, "right"), (50, "down"), (52, "left")],end_time = 54):Maze: col: 01234 0: ..... <-- start at (0, 0) 1: .###. 2: ..... <-- ends at (2, 2) Interval [0, 2): before first event -> "flat" skipped, ball stays at (0, 0) Interval [2, 50): state = "right", remaining_seconds = 50 - 2 = 48 4 steps move (0, 0) -> (0, 1) -> (0, 2) -> (0, 3) -> (0, 4) (remaining = 44) next cell (0, 5) is out of bounds -> loop stops immediately! (44 idle seconds skipped) Interval [50, 52): state = "down", remaining_seconds = 52 - 50 = 2 step 1: (1, 4) is '.' -> move to (1, 4), remaining = 1 step 2: (2, 4) is '.' -> move to (2, 4), remaining = 0 -> loop ends Interval [52, 54): state = "left", remaining_seconds = 54 - 52 = 2 step 1: (2, 3) is '.' -> move to (2, 3), remaining = 1 step 2: (2, 2) is '.' -> move to (2, 2), remaining = 0 -> loop ends Final answer: [2, 2]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # DIRECTIONS: maps tilt state -> (delta_row, delta_col) on the grid # where row 0 is the top edge and col 0 is the left edge. DIRECTIONS: Dict[str, Tuple[int, int]] = { "up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1), } def is_open_cell(maze: list[str], row: int, col: int) -> bool: """Return True if (row, col) lies inside the maze bounds and is not a '#' wall.""" # Explicit >= 0 checks are essential because maze[-1] in Python wraps around # to the last row/column instead of acting like an out-of-bounds wall. if row < 0 or row >= len(maze) or col < 0 or col >= len(maze[0]): return False return maze[row][col] == "." def ball_position(maze: list[str], start: list[int], events: list[tuple[int, str]], end_time: int) -> list[int]: # row, col: current coordinates of the ball; before events[0], the board is "flat" # so the ball stays at `start` with zero movement to simulate. row, col = start[0], start[1] num_events = len(events) for i in range(num_events): interval_start, state = events[i][0], events[i][1] # Only whole seconds 0 .. end_time - 1 are simulated, and event times are strictly # increasing, so an event at `end_time` or later (and everything after it) never fires. if interval_start >= end_time: break # Phase 1: find when this constant-tilt interval stops—either at the next event # or at `end_time`, whichever comes first. interval_end = end_time if i + 1 < num_events and events[i + 1][0] < end_time: interval_end = events[i + 1][0] remaining_seconds = interval_end - interval_start if state == "flat": continue # Phase 2: roll one cell per second in `state`'s direction. Even if `remaining_seconds` # is 10^9, the ball hits a '#' wall or grid edge in at most max(rows, cols) - 1 <= 99 # steps, immediately stopping this loop. dr, dc = DIRECTIONS[state] while remaining_seconds > 0 and is_open_cell(maze, row + dr, col + dc): row += dr col += dc remaining_seconds -= 1 return [row, col]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine tilting a small wooden labyrinth box to the left and holding it there for ten minutes: the marble rolls across a few inches of open track, clicks against a wooden wall, and then sits completely motionless for the remaining nine minutes and fifty-nine seconds. Instead of watching a clock tick every single second, we only need to jump from one tilt event to the next, rolling the ball during each constant-tilt interval until either that interval's timer runs out or a wall stops the ball early.
A naive second-by-second simulation loops from s = 0 up to end_time - 1 and checks the ball's neighbor on every tick. Because end_time can be 10^9, that loop runs up to a billion iterations and times out, wasting almost all of its time checking the exact same wall cell over and over while the ball is already stuck. By grouping time into intervals between consecutive events and stopping each roll the moment is_open_cell returns False, a 100 × 100 board never takes more than 99 steps per event—even if an interval lasts a billion seconds.
Walk through a tiny example on a 1 × 5 open corridor maze = ["....."] starting at [0, 0], with events = [(1, "right"), (500, "left")] and end_time = 502:
- Seconds
[0, 1)happen before the first event, so the board is"flat"and the ball stays at[0, 0]. - Event
(1, "right")covers[1, 500)(499seconds). The ball steps right4times to[0, 4], sees[0, 5]is out of bounds, and stops immediately—skipping the remaining495idle seconds. - Event
(500, "left")is clamped to[500, 502)(2seconds). The ball steps left2times to[0, 2], and the timer runs out, returning[0, 2].
Complexity
Let E be the number of events (E <= 10^4), R be the number of rows (R <= 100), and C be the number of columns (C <= 100).
- Time —
O(E * max(R, C)): We iterate through theEevents once; inside each event's interval, thewhileloop advances the ball in one straight line without turning, so it can step at mostmax(R, C) - 1cells before hitting a'#'wall or the edge of the grid. At the maximum constraints (10^4events on a100 × 100grid), this performs under10^6constant-time grid checks, completely independent ofend_time. - Space —
O(1): Beyond the input arguments, we store only a handful of integer coordinates and loop variables (row,col,interval_start,interval_end,remaining_seconds).
Edge cases
end_time = 0: Zero seconds elapse, so0 >= end_timebreaks immediately on any event at time0and returns[start[0], start[1]].- Empty
eventsor late first event: The board starts"flat", so any time beforeevents[0]leaves the ball atstartwith no special-case code needed. - Event at
time >= end_time: Because only seconds0 .. end_time - 1are simulated, an event attime == end_time(such as(4, "right")whenend_time = 4in Example 3) has zero seconds to act and is ignored. - Clamping the final active interval: When the next event is after
end_time(or does not exist),interval_endis capped atend_timeso the ball stops rolling at the exact end timestamp. - Tilt ending mid-corridor: When
remaining_secondsreaches0before the ball hits a wall, thewhilecondition stops the ball right in the middle of the open corridor. - Mazes without border
'#'walls: Grid edges act as walls viais_open_cell(row < 0,row >= R,col < 0,col >= C), including a1 × 1maze["."]where the ball can never move. - Repeated same-direction or
"flat"events: Back-to-back"right"events seamlessly continue rolling from the current[row, col], and"flat"intervals skip straight to the next event inO(1)time.
Common mistakes
- Looping from
0toend_time: Simulating each second individually takesO(end_time)time and times out wheneverend_timeapproaches10^9. - Using
<instead of<=when stopping atend_time: Writingif interval_start > end_time: breakmistakenly processes an event attime == end_time(though its clamped duration would be0, failing to clampinterval_endtoend_timeas well will roll the ball past the end). - Forgetting to clamp
interval_endtoend_time: Usingevents[i + 1][0] - events[i][0]whenevents[i + 1][0] > end_timelets the ball keep rolling afterend_time. - Omitting
row < 0orcol < 0checks in Python: Without explicit negative-index guards,maze[row - 1][col]atrow = 0evaluatesmaze[-1][col]and teleports the ball to the bottom row! - Swapping row and column deltas:
"up"decreasesrow((-1, 0)), whereas"left"decreasescol((0, -1)).
Alternative approaches
- Precomputed distance-to-wall tables: Four linear sweeps over the grid in
O(R * C)time can precomputedist[dir][r][c], the exact number of open cells from(r, c)to the nearest wall in each of the four directions. Each event interval then jumpssteps = min(remaining_seconds, dist[state][row][col])cells inO(1)arithmetic (row += dr * steps,col += dc * steps), reducing total runtime toO(R * C + E). ForR, C <= 100, the directwhileroll is already under99steps and far simpler to write bug-free in a live interview.
Follow-up questions
- How would you answer
Qindependentend_timequeries against the same maze, starting cell, and event schedule? Pre-simulate allEevents once and storepos_at_event[i], the marble's[row, col]at the start ofevents[i]. For each queryT, use binary search (repeatedly halving a sorted range to find a boundary in logarithmic steps) to find the last eventiwithevents[i][0] < T; if none exists, returnstart, and otherwise start frompos_at_event[i]and roll forT - events[i][0]seconds inO(log E + max(R, C))time per query (orO(log E)with precomputed wall distances). - If the board measured
10^5by10^5and onlyWobstacle coordinates were given instead of a dense grid, how would you adapt your algorithm? You cannot allocate a10^10-cell grid or step one cell at a time across10^5columns. Instead, build a dictionary mapping each row index to a sorted list of obstacle column indices in that row (plus-1andcolsfor the borders), and likewise each column index to its sorted obstacle row indices; then each tilt event binary-searches the current row or column's obstacle list to find the next wall inO(log W)time and jumpsmin(remaining_seconds, gap_to_wall)cells in one calculation. - What testing strategy would you use in a live interview to catch off-by-one timestamp and boundary bugs? Write the literal
10-line second-by-second simulator (for s in range(end_time)) and compare its output againstball_positionon a few hundred tiny random5 × 5grids withend_time <= 45, which catches off-by-one timing or boundary bugs immediately. Pair that with targeted unit tests forend_time = 0, an event attime == end_time, grids without border'#'walls, and one max-scale test (end_time = 10^9,10^4events) to verify performance.
Follow-up questions
- How would you answer `Q` independent `end_time` queries against the same maze, starting cell, and event schedule?
- If the board measured `10^5` by `10^5` and only `W` obstacle coordinates were given instead of a dense grid, how would you adapt your algorithm?
- What testing strategy would you use in a live interview to catch off-by-one timestamp and boundary bugs?
Similar questions
- Structuring Implementation-Heavy Data Structures
- Task Completion Timestamps on a Bounded Single-Worker Queue
- Verify Root-to-Leaf Path Sum
- Counting Index Pairs Equivalent Under Repeated Digit Reversals
- Permutation Inversion Counter
- Unique Three-Letter Substrings Containing a Vowel
More Hudson River Trading interview questions
- Counting Binary-Digit Base-4 Integers Below N Medium
- Track Sentry Simulation and Manual Integer Formatting Medium
- Structuring Implementation-Heavy Data Structures Medium Pro
- End-to-End Cardiac Risk Classification Workflow Hard Pro
- Verify Root-to-Leaf Path Sum Easy Pro
- Sample Mean vs. Median Under Zero-Inflated Normals Medium Pro
- Lifecycle-Tracked Lazy File Streaming in Python Medium Pro
- Counting Arrivals Past a Switching Lookout Easy Pro
- Aligned Slab-Backed Pool Allocator Design Medium Pro
- Systematic Custom Test Suite Design Under Coding Assessment Time Limits Medium Pro