Sliding Token on a Grid with Timed Heading Changes
Arrays & HashingAuto-graded · 21 test casesLast updated
Compute a token's final cell on a grid with blocked cells when its heading changes at given timestamps up to 10^9, which requires processing time segments instead of simulating each tick.
A token sits on a rectangular board. A schedule of timed commands controls which way it heads: up, down, left or right. While a heading is active, the token tries to advance one cell per tick. If the next cell in that heading cannot be entered, the token stays where it is until a later command changes the heading.
Given the board, the starting cell, the schedule and a final time, return the token's cell at the final time.
Board legend (read carefully): the character 'o' is a free cell the token may enter, and the character '.' is a wall the token can never enter.
Function signature
def final_position(grid: List[str], start: List[int], actions: List[Tuple[int, str]], end_time: int) -> List[int]:
start is [row, col]. Each command is a pair (time, direction).
Rules
- Row
0is the top row and column0is the leftmost column. From(row, col),"up"leads to(row - 1, col),"down"to(row + 1, col),"left"to(row, col - 1), and"right"to(row, col + 1). - Before the first command the token is idle. A command
(t, d)makesdthe active heading starting at tickt, and it remains active until the next command takes over. - Time is measured in whole ticks. For each tick
s = 0, 1, ..., end_time - 1, the active heading is the one from the command with the largesttime <= s. If no command qualifies, the token does not move in that tick. - If a heading is active and the adjacent cell in that heading lies inside the board and is
'o', the token moves into it at the end of that tick. Otherwise it stays put. - Anything outside the board counts as a wall, so the token never leaves the board.
- Commands with
time >= end_timehave no effect. - Return the token's
[row, col]after tickend_time - 1has been processed, that is, at timeend_time. Ifend_timeis0, returnstart.
Constraints
1 <= len(grid) <= 500and1 <= len(grid[0]) <= 500; all rows have equal length and contain only'o'and'.'.startis a free ('o') cell inside the board.0 <= len(actions) <= 10^50 <= time <= 10^9for each command, and command times are strictly increasing.- Each direction is one of
"up","down","left","right". 0 <= end_time <= 10^9
Examples
Example 1
Input: final_position(['ooooo', 'o.o.o', 'ooooo'], [0, 0], [[0, 'right'], [3, 'down'], [5, 'left']], 7)
Output: [0, 1]
Example 2
Input: final_position(['ooooo', 'o.o.o', 'ooooo'], [2, 4], [[2, 'left'], [4, 'up'], [50, 'right']], 60)
Output: [0, 4]
Example 3
Input: final_position(['ooo'], [0, 2], [[0, 'left'], [1, 'right'], [3, 'left']], 3)
Output: [0, 2]
Hints
Hint 1
end_time can reach 10^9, so stepping through every tick is too slow. The heading only changes at command times, so think in terms of the stretches between commands.
Hint 2
Command i controls the half-open time range [t_i, t_{i+1}), and the last remaining command controls [t_last, end_time). Discard commands with time >= end_time first. Inside one stretch the heading is fixed, so the token travels along a straight line.
Hint 3
Within a stretch, advance while you have time budget left and the next cell is inside the board and equal to 'o'. The moment it is blocked, stop that stretch, because nothing can change until the next command. Remember that 'o' is free and '.' is a wall.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulating every tick is impossible because end_time may be 10^9. The heading changes only at command times, so split the timeline into stretches:
- Drop every command with
time >= end_time, since it cannot affect any simulated tick. - Command
igoverns the half-open range[t_i, t_{i+1}); the last remaining command governs[t_last, end_time). - Ticks before the first command have no heading, so nothing moves. Starting the loop at the first command handles this automatically.
- For each stretch, the budget is
stop - tticks. Repeatedly look at the neighboring cell in the active heading. If it is inside the board and equals'o', move into it and spend one tick. Otherwise stop the stretch.
Why it is correct
- Since times are strictly increasing, the last command with
time <= sis exactly commandifor every ticksin[t_i, t_{i+1}), so each tick uses the right heading. - Stopping early on a block is safe: the token's position, the heading and the board are all unchanged for the rest of the stretch, so the same neighbor would be found blocked at every remaining tick.
- Each successful move consumes exactly one tick, so spending the budget one move at a time matches the rules exactly.
- Discarding commands at or after
end_timeis valid because they only affect ticks that are never simulated, and it makes the last remaining stretch end atend_time. - Testing
== 'o'(rather than comparing against'.'loosely) and checking bounds before indexing prevents both legend mistakes and negative-index wraparound.
Complexity
- Time: each stretch moves along a straight line, so it makes at most
max(m, n) - 1moves. The total isO(A * max(m, n))withA = len(actions), independent ofend_time. - Space:
O(A)for the filtered command list.
An optional speedup is to precompute, for each cell and direction, how many consecutive free cells follow. Each stretch then becomes O(1) by moving min(budget, run_length) cells, giving O(mn + A) overall.
Reference solution
from typing import List, Tuple
def final_position(grid: List[str], start: List[int], actions: List[Tuple[int, str]], end_time: int) -> List[int]:
m, n = len(grid), len(grid[0])
r, c = start[0], start[1]
deltas = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}
# Only commands strictly before end_time can influence a simulated tick.
acts = [(int(a[0]), a[1]) for a in actions if a[0] < end_time]
for i, (t, d) in enumerate(acts):
stop = acts[i + 1][0] if i + 1 < len(acts) else end_time
steps = stop - t
dr, dc = deltas[d]
while steps > 0:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 'o':
r, c = nr, nc
steps -= 1
else:
break
return [r, c]