Grid Walker with Blocked Cells
Arrays & HashingAuto-graded · 24 test casesLast updated
Tests simulation with hash-based obstacle lookup, movement logic, and tracking a running maximum over coordinate positions.
You control a walker on an infinite two-dimensional grid. The walker begins at the origin (0, 0).
You are given:
- A string
moveswhere each character is one of'U','D','L', or'R', representing up, down, left, or right respectively. - A list
blockedof coordinate pairs[x, y]representing cells the walker cannot enter.
Process each character in moves from left to right. For each move command:
- Calculate the cell the walker would step into (one unit in the indicated direction).
- If that cell appears in
blocked, the walker stays at its current position for this command. - Otherwise, the walker moves into that cell.
After processing every character, return the maximum squared Euclidean distance from the origin that the walker reached at any point during the journey (including the starting position).
The squared Euclidean distance of a cell (x, y) is x² + y².
Constraints
0 ≤ len(moves) ≤ 100,0000 ≤ len(blocked) ≤ 100,000- Each character in
movesis'U','D','L', or'R' - Blocked cell coordinates satisfy
-100,000 ≤ x, y ≤ 100,000 - Blocked cells may contain duplicates
- The origin
(0, 0)may appear in the blocked list (the walker still starts there)
Examples
Example 1
Input: grid_walk_max_distance('URR', [])
Output: 5
Example 2
Input: grid_walk_max_distance('UUDL', [[0, 2]])
Output: 1
Example 3
Input: grid_walk_max_distance('RRUUL', [[2, 1]])
Output: 4
Example 4
Input: grid_walk_max_distance('UDLR', [[0, 1], [1, 0], [-1, 0], [0, -1]])
Output: 0
Hints
Hint 1
Store blocked cells in a data structure that supports fast membership checks—what structure gives O(1) lookups?
Hint 2
Track the maximum squared distance throughout the entire walk, not just at the end, since the walker may move closer to the origin later.
Hint 3
A blocked move means the walker skips that command and continues with the next one; it does not halt the entire simulation.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simulating each step of the walker's journey while efficiently checking whether cells are blocked.
The core insight is that checking "is this cell blocked?" must be fast. With up to 100,000 moves and 100,000 blocked cells, a naive approach of scanning the blocked list for each move would require O(n·m) operations—up to 10 billion checks, which is too slow.
Instead, convert the blocked cell list into a hash set of coordinate tuples during preprocessing. Python tuples are immutable and hashable, making them perfect dictionary keys. This gives us O(1) expected-time membership checks.
The simulation then proceeds as follows:
- Build a set containing all blocked cell coordinates as tuples
- Initialize the walker at
(0, 0)withmax_dist = 0(the squared distance of the origin) - Create a direction lookup table mapping each command character to its
(dx, dy)offset - For each command in the moves string:
- Compute the candidate next cell by adding the direction offset to the current position
- Check if the candidate cell is in the blocked set
- If not blocked: update the walker's position and recalculate the maximum squared distance
- If blocked: do nothing and continue to the next command
- Return the maximum squared distance encountered
Why this is correct:
- We faithfully simulate every command in sequence, moving exactly one cell per unblocked command
- The maximum is tracked after every successful move, capturing the peak distance even if the walker later returns toward the origin
- Using squared distance avoids floating-point arithmetic while preserving the ordering (since square root is monotonic)
- Starting with
max_dist = 0correctly accounts for the origin itself
Time Complexity: O(n + m) where n is the length of moves and m is the number of blocked cells. Building the set takes O(m), and each of the n moves requires O(1) expected time for the hash lookup.
Space Complexity: O(m) for storing the blocked cell coordinates in the hash set.
from typing import List
def grid_walk_max_distance(moves: str, blocked: List[List[int]]) -> int:
blocked_set = {(x, y) for x, y in blocked}
x, y = 0, 0
max_dist = 0
direction_map = {
'U': (0, 1),
'D': (0, -1),
'L': (-1, 0),
'R': (1, 0)
}
for move in moves:
dx, dy = direction_map[move]
next_x, next_y = x + dx, y + dy
if (next_x, next_y) not in blocked_set:
x, y = next_x, next_y
max_dist = max(max_dist, x * x + y * y)
return max_dist