KatInterview

Collect Characters by Walking a Grid

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingmatrixsimulationstring-building

Last 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 strings
  • start_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:

  1. Begin at the starting position and collect the character there
  2. Execute each command in order, moving to the next cell
  3. Collect the character at each newly visited cell
  4. When collecting characters, skip any character that is identical to the most recently collected character (run-length collapsing)
  5. Return the collected string, or None if any error occurs

Obstacles and Errors:

  • Cells containing '#' are blocked and cannot be entered
  • Return None if:
    • 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