KatInterview

Grid Walker with Blocked Cells

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingsimulationhash-setgrid

Last 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 moves where each character is one of 'U', 'D', 'L', or 'R', representing up, down, left, or right respectively.
  • A list blocked of 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,000
  • 0 ≤ len(blocked) ≤ 100,000
  • Each character in moves is '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.