Collect Characters by Walking a Grid
Arrays & HashingAuto-graded · 22 test casesLast updated
Tests grid traversal with directional commands, run-length encoding, and boundary/obstacle validation.
You are given a 2D grid of characters, a starting position, and a sequence of directional commands. Your task is to walk through the grid following the commands and collect characters along the way.
Task:
Write a function that takes:
grid: a 2D list of single-character stringsstart_row,start_col: the initial position (0-indexed)commands: a string of directional moves where each character is'U'(up),'D'(down),'L'(left), or'R'(right)
The function should:
- Begin at the starting position and collect the character there
- Execute each command in order, moving to the next cell
- Collect the character at each newly visited cell
- When collecting characters, skip any character that is identical to the most recently collected character (run-length collapsing)
- Return the collected string, or
Noneif any error occurs
Obstacles and Errors:
- Cells containing
'#'are blocked and cannot be entered - Return
Noneif:- The starting position is out of bounds or blocked
- Any command is not one of
'U','D','L','R' - Any move would go out of bounds
- Any move would enter a blocked cell
Constraints:
1 ≤ rows, cols ≤ 1000(if the grid is valid)0 ≤ len(commands) ≤ 10000- Each cell contains a single printable ASCII character
- Grid may be empty or have empty rows (both are invalid)
- Negative indices are considered out of bounds
Examples
Example 1
Input: collect_characters([['a', 'b', 'b'], ['#', 'c', 'd'], ['e', 'f', 'd']], 0, 0, 'RRDLD')
Output: 'abdcf'
Example 2
Input: collect_characters([['a', '#'], ['b', 'c']], 0, 0, 'R')
Output: None
Example 3
Input: collect_characters([['x', 'x'], ['x', 'y']], 0, 0, 'RDLU')
Output: 'xyx'
Hints
Hint 1
Start by validating the starting position before processing any moves
Hint 2
Use a dictionary to map each direction character to its row and column delta
Hint 3
Build the result using a list and join at the end to avoid quadratic string concatenation
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simulating a walk through a 2D grid while collecting characters and applying run-length encoding (collapsing consecutive duplicate characters).
The solution follows these steps:
- Validate the grid structure: Check that the grid is non-empty and has consistent row lengths
- Validate the starting position: Ensure it's within bounds and not blocked
- Initialize tracking variables: Current position and a list to accumulate characters
- Collect the starting character: Add it to the result
- Process each command:
- Map the command character to a direction delta using a dictionary
- Calculate the target position
- Validate the move (bounds check and obstacle check)
- Move to the new position
- Collect the character if it differs from the last collected one
- Return the result: Join the character list into a string
The key insight is to validate each move before committing to it, and to only append characters that differ from the most recently collected character.
Why It Works
The algorithm maintains an invariant: at each step, the current position is valid (in bounds and not blocked), and the result contains the deduplicated sequence of all characters visited so far.
- Base case: The starting position is validated upfront, ensuring the first character collection is safe
- Inductive step: Each command is validated before moving, so we never enter an invalid state. Characters are only appended when they differ from the previous one, implementing exact run-length collapsing
Returning None at the first error ensures no partial or corrupted results escape.
Complexity
Let k = len(commands) and m × n be the grid dimensions.
-
Time: O(k). Each command requires constant-time operations: dictionary lookup, arithmetic, bounds checking, and character comparison. The final join operation is O(result length) ≤ O(k + 1). The grid size doesn't affect runtime since we never scan the entire grid.
-
Space: O(k). The result list can hold at most
k + 1characters (the starting position plus one per command). All other variables use constant space.
Solution Code
from typing import List, Optional
def collect_characters(grid: List[List[str]], start_row: int, start_col: int, commands: str) -> Optional[str]:
if not grid or not grid[0]:
return None
rows = len(grid)
cols = len(grid[0])
if any(len(row) != cols for row in grid):
return None
if not (0 <= start_row < rows and 0 <= start_col < cols):
return None
if grid[start_row][start_col] == '#':
return None
row, col = start_row, start_col
result = []
last_char = None
def add_character(ch: str) -> None:
nonlocal last_char
if ch != last_char:
result.append(ch)
last_char = ch
add_character(grid[row][col])
direction_map = {
'U': (-1, 0),
'D': (1, 0),
'L': (0, -1),
'R': (0, 1),
}
for cmd in commands:
if cmd not in direction_map:
return None
delta_row, delta_col = direction_map[cmd]
new_row, new_col = row + delta_row, col + delta_col
if not (0 <= new_row < rows and 0 <= new_col < cols):
return None
if grid[new_row][new_col] == '#':
return None
row, col = new_row, new_col
add_character(grid[row][col])
return ''.join(result)