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 to state starting at timestamp t, 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 second s, the active inclination is the state set by the latest event satisfying t <= s (or "flat" if none exists).
  • When the inclination during second s is "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 second s; if the neighbor is out of bounds or contains '#', the marble remains in its current cell.
  • Any event with t >= end_time fires at or after termination and has no effect. If end_time == 0, zero seconds elapse and the marble stays at start.

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) <= 100 and 1 <= len(maze[0]) <= 100; all strings in maze share 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) in events, 0 <= t <= 10^9, timestamps t are strictly increasing, and state is in {"up", "down", "left", "right", "flat"}.
  • 0 <= end_time <= 10^9

Step-by-step walkthrough

  1. Understand the grid and timing rules

    We are given a rectangular grid maze of '#' (wall) and '.' (open cell), a starting position start = [row, col], a list of strictly increasing (time, state) events, and an integer end_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 - 1 happen. If end_time == 0, zero seconds pass and the ball stays at start. Any event with time >= end_time has no effect.
    • Board state: Before the first event, the board is "flat" (the ball never moves). An event (t, state) sets the board to state starting at second t until the next event.
    • Rolling and walls: During each tilted second, the ball moves 1 cell in that direction if the target cell is inside the grid and '.'. Grid boundaries act just like '#' walls.
  2. 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), but end_time can be as large as 10^9—a billion loop iterations will time out in Python.

    Why is that loop wasting so much work? Suppose the maze is 100 × 100 and an event tilts the board "left" for 900,000,000 seconds. Within at most 99 seconds, the ball rolls into a wall or the left border of the grid—and for the remaining 899,999,901 seconds it just sits pressed against that wall doing nothing!

  3. 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:

    1. Before events[0], the board is "flat", so the ball stays at start—we can skip [0, t0) completely.
    2. If an interval's state is "flat", nothing moves—skip the whole interval in O(1) time.
    3. If an interval tilts in direction (dr, dc), the ball rolls straight ahead one cell per second until either remaining_seconds hits 0 or 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 most 99 steps before hitting a wall or grid border. Even with 10^4 events and end_time = 10^9, the total number of single-cell steps across the entire run is at most 10^4 × 99 < 10^6.

  4. Check grid bounds safely

    Before moving into (next_row, next_col), we need a helper is_open_cell. In Python, negative list indices like maze[-1] silently wrap around to the last row instead of raising an error! Checking row < 0 and col < 0 explicitly 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] == "."
    
  5. Slice each event interval and roll until blocked

    For event i starting at interval_start = events[i][0]:

    • Early exit (interval_start >= end_time): Because event times are strictly increasing and only seconds 0 .. end_time - 1 count, an event at end_time or later never takes effect, so we break.
    • Clamp the end (interval_end): The tilt lasts until the next event events[i + 1][0], or end_time if there is no next event (or if the next event happens after end_time). Clamping to end_time prevents the last active tilt from rolling the ball past the end of the simulation.
    • Bounded while roll: 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]
    
  6. 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]
    
  7. 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:

  1. Seconds [0, 1) happen before the first event, so the board is "flat" and the ball stays at [0, 0].
  2. Event (1, "right") covers [1, 500) (499 seconds). The ball steps right 4 times to [0, 4], sees [0, 5] is out of bounds, and stops immediately—skipping the remaining 495 idle seconds.
  3. Event (500, "left") is clamped to [500, 502) (2 seconds). The ball steps left 2 times 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 the E events once; inside each event's interval, the while loop advances the ball in one straight line without turning, so it can step at most max(R, C) - 1 cells before hitting a '#' wall or the edge of the grid. At the maximum constraints (10^4 events on a 100 × 100 grid), this performs under 10^6 constant-time grid checks, completely independent of end_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, so 0 >= end_time breaks immediately on any event at time 0 and returns [start[0], start[1]].
  • Empty events or late first event: The board starts "flat", so any time before events[0] leaves the ball at start with no special-case code needed.
  • Event at time >= end_time: Because only seconds 0 .. end_time - 1 are simulated, an event at time == end_time (such as (4, "right") when end_time = 4 in 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_end is capped at end_time so the ball stops rolling at the exact end timestamp.
  • Tilt ending mid-corridor: When remaining_seconds reaches 0 before the ball hits a wall, the while condition stops the ball right in the middle of the open corridor.
  • Mazes without border '#' walls: Grid edges act as walls via is_open_cell (row < 0, row >= R, col < 0, col >= C), including a 1 × 1 maze ["."] 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 in O(1) time.

Common mistakes

  • Looping from 0 to end_time: Simulating each second individually takes O(end_time) time and times out whenever end_time approaches 10^9.
  • Using < instead of <= when stopping at end_time: Writing if interval_start > end_time: break mistakenly processes an event at time == end_time (though its clamped duration would be 0, failing to clamp interval_end to end_time as well will roll the ball past the end).
  • Forgetting to clamp interval_end to end_time: Using events[i + 1][0] - events[i][0] when events[i + 1][0] > end_time lets the ball keep rolling after end_time.
  • Omitting row < 0 or col < 0 checks in Python: Without explicit negative-index guards, maze[row - 1][col] at row = 0 evaluates maze[-1][col] and teleports the ball to the bottom row!
  • Swapping row and column deltas: "up" decreases row ((-1, 0)), whereas "left" decreases col ((0, -1)).

Alternative approaches

  • Precomputed distance-to-wall tables: Four linear sweeps over the grid in O(R * C) time can precompute dist[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 jumps steps = min(remaining_seconds, dist[state][row][col]) cells in O(1) arithmetic (row += dr * steps, col += dc * steps), reducing total runtime to O(R * C + E). For R, C <= 100, the direct while roll is already under 99 steps and far simpler to write bug-free in a live interview.

Follow-up questions

  • How would you answer Q independent end_time queries against the same maze, starting cell, and event schedule? Pre-simulate all E events once and store pos_at_event[i], the marble's [row, col] at the start of events[i]. For each query T, use binary search (repeatedly halving a sorted range to find a boundary in logarithmic steps) to find the last event i with events[i][0] < T; if none exists, return start, and otherwise start from pos_at_event[i] and roll for T - events[i][0] seconds in O(log E + max(R, C)) time per query (or O(log E) with precomputed wall distances).
  • 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? You cannot allocate a 10^10-cell grid or step one cell at a time across 10^5 columns. Instead, build a dictionary mapping each row index to a sorted list of obstacle column indices in that row (plus -1 and cols for 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 in O(log W) time and jumps min(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 against ball_position on a few hundred tiny random 5 × 5 grids with end_time <= 45, which catches off-by-one timing or boundary bugs immediately. Pair that with targeted unit tests for end_time = 0, an event at time == end_time, grids without border '#' walls, and one max-scale test (end_time = 10^9, 10^4 events) to verify performance.

Follow-up questions

Similar questions

More Hudson River Trading interview questions

All 55 Hudson River Trading questions →