KatInterview

Grid Obstacle Distances and Palindrome Ancestor Paths

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgridbit-manipulationdfs

Last updated

Tests two skills at once: directional obstacle scanning on a 2D grid, and bitmask-based palindrome counting over rooted-tree ancestor segments.

Part 1 — Obstacle Clearance Signatures

You are given a 2D grid of characters. Each cell is either an obstacle ('#') or open space (any other character). For every open cell, define its clearance signature as a list of four integers [left, up, right, down], where each value is the number of steps from that cell to the nearest obstacle in that direction, searching only within the same row (for left/right) or column (for up/down).

Disqualification rule: if there is no obstacle between an open cell and the grid boundary in some direction, the cell has no valid clearance value in that direction. Such a cell cannot match any integer target and must be excluded from the results regardless of the other three directions.

Given the grid and a target signature sig (a list of exactly four positive integers [left, up, right, down]), return a list of all [row, col] positions whose clearance signature exactly matches sig. Results must appear in row-major order: top to bottom, and left to right within each row.

Clearance value definition: the clearance value in a direction is the count of steps (cells) between the open cell and the nearest obstacle in that direction. An obstacle immediately adjacent contributes a clearance of 1. Only '#' cells are obstacles; every other character (including '.' and letters) is open space.


Part 2 — Palindrome-Capable Ancestor Segments

You are given a rooted tree of n nodes numbered 0 through n − 1, with node 0 as the root. Each node i stores a single lowercase letter letters[i]. Edges are given as two parallel arrays edge_from and edge_to; each pair (edge_from[i], edge_to[i]) is an undirected edge.

For a query node q, consider every path segment that starts at q and ends at q or one of its ancestors (so the segment travels upward toward the root). Concretely, the valid end nodes for query q are: q itself, the parent of q, the grandparent of q, and so on up to and including the root (node 0). Each such segment collects the letters of every node along it, inclusive of both endpoints.

A multiset of letters can be rearranged into a palindrome when at most one letter has an odd total frequency.

For each query node q, count how many of those upward segments are palindrome-capable and return one integer per query.

Example: tree with 4 nodes, letters = ['z','a','a','a'], edges 0-1, 0-2, 1-3, query node 3.

  • The path from root to node 3 is 0 → 1 → 3 with letters z, a, a.
  • Upward segments from node 3:
    • Ends at 3 → letters {a} → one distinct letter, frequency 1 (odd) → at most one odd → palindrome-capable
    • Ends at 1 → letters {a, a} → frequency of a is 2 (even) → zero odd frequencies → palindrome-capable
    • Ends at 0 → letters {a, a, z} → a even, z odd → one odd frequency → palindrome-capable
  • Answer for query 3: 3

Return Value

Return a single dictionary with exactly these two keys:

{
    "robot_locations": [[r1, c1], [r2, c2], ...],
    "palindrome_counts": [count_for_query_0, count_for_query_1, ...]
}

palindrome_counts must have one entry per element of queries, in the same order.


Constraints

  • 1 <= len(grid) <= 300; all rows have equal length; 1 <= len(grid[0]) <= 300
  • sig has exactly 4 positive integers in order [left, up, right, down]
  • 1 <= n <= 10^5
  • letters has exactly n lowercase ASCII letters; letters[i] is the letter stored at node i
  • edge_from and edge_to each have exactly n − 1 entries (or 0 entries when n = 1)
  • The edges form a valid undirected tree rooted at node 0
  • 0 <= queries[i] < n; len(queries) <= 10^5; duplicate query values are allowed

Examples

Example 1

Input: solve_two_problems(['#####', '#...#', '#.#.#', '#...#', '#####'], [1, 1, 3, 3], 4, ['z', 'a', 'a', 'a'], [0, 0, 1], [1, 2, 3], [3])

Output: {'robot_locations': [[1, 1]], 'palindrome_counts': [3]}

Example 2

Input: solve_two_problems(['#######', '#..#..#', '#..#..#', '#######'], [1, 1, 1, 1], 1, ['a'], [], [], [0])

Output: {'robot_locations': [], 'palindrome_counts': [1]}

Hints

Hint 1

For Part 1, skip the O(R·C·(R+C)) outward scan. Run four single-pass sweeps instead — left-to-right, right-to-left, top-to-bottom, bottom-to-top — each carrying a 'last obstacle seen' index. A cell that has never seen an obstacle in some direction keeps a None distance, which can never equal an integer target, so the disqualification rule costs nothing extra.

Hint 2

For Part 2, encode the character frequencies along a root-to-node path as a 26-bit XOR mask: bit k flips every time letter k is added. A segment from node q up to ancestor a is palindrome-capable when the XOR of their two prefix masks has at most one bit set — so check 27 possible target masks (the all-zero mask and each of the 26 single-bit masks) against a running frequency dictionary.

Hint 3

Use an iterative DFS with an explicit backtracking 'exit' frame to avoid Python's recursion limit on deep trees. Maintain a dictionary from prefix mask to its occurrence count on the active root-to-current-node path, initialised with {0: 1} to represent the empty prefix above the root; update it on entry and undo the update on exit.