Grid Obstacle Distances and Palindrome Ancestor Paths
Trees & GraphsAuto-graded · 17 test casesLast 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
3is0 → 1 → 3with lettersz, 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 ofais 2 (even) → zero odd frequencies → palindrome-capable - Ends at
0→ letters{a, a, z}→aeven,zodd → one odd frequency → palindrome-capable
- Ends at
- 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]) <= 300sighas exactly 4 positive integers in order[left, up, right, down]1 <= n <= 10^5lettershas exactlynlowercase ASCII letters;letters[i]is the letter stored at nodeiedge_fromandedge_toeach have exactlyn − 1entries (or 0 entries whenn = 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1 — Grid Clearance Signatures
The naive approach scans outward from every open cell in all four directions, which costs O(R·C·(R+C)) — too slow for a 300×300 grid. The efficient path is four linear sweeps, each carrying a single "last obstacle seen" index:
- Left sweep: iterate each row left to right. When a
'#'is encountered, record its column aslast. For each subsequent open cell at columnc,left[r][c] = c − last. - Right sweep: same row, right to left,
right[r][c] = last − c. - Up sweep: iterate each column top to bottom, same idea with rows.
- Down sweep: same column, bottom to top.
Any open cell where last was never set in some direction retains None for that entry. Because sig contains integers, a None can never match, so the disqualification rule costs nothing extra.
After the four sweeps, one final pass compares [left, up, right, down] against sig for every open cell. Matches are collected in row-major order.
Time: O(R·C) — four passes over the grid.
Space: O(R·C) for the four distance tables.
Part 2 — Palindrome-Capable Ancestor Segments
A string can be rearranged into a palindrome when at most one character has an odd frequency. Represent the cumulative character frequencies on a root-to-node path as a 26-bit XOR mask: bit k flips each time the k-th letter is added. Call the mask at node v after including v's own letter mask(v), and define mask(empty) = 0 for the imaginary empty prefix above the root.
The segment from query node q up to ancestor a carries the characters of every node from q to a inclusive. Its parity mask equals mask(q) XOR mask(parent(a)). That segment is palindrome-capable when this XOR has at most one bit set — which means we need to count, among all prefix masks currently on the root-to-q path (including the empty prefix 0), how many differ from mask(q) by zero bits or by exactly one bit. That is 27 hash-map lookups.
The algorithm runs an iterative DFS (required to avoid Python's recursion limit on chains of 10⁵ nodes):
- Maintain
counts, a dictionary from prefix mask to how many times it currently appears on the active path. Initialise it with{0: 1}so the full segment fromqto the root is counted. - On entering node
v, computemask(v), do 27 lookups to get its answer, addmask(v)tocounts, then push a backtracking "exit" frame onto the stack. - The exit frame decrements (and cleans up)
mask(v)fromcountswhen the DFS leavesv.
Because the exit frame stores mask(v) at push time, the dictionary is always in the exact state needed for the subtree being explored.
Time: O(27·N + Q) — 27 dictionary lookups per node, one answer lookup per query.
Space: O(N) for the adjacency list; counts is bounded by the current tree depth.
Edge Cases
- A grid with no
'#'at all returns[]— every cell has at least oneNonedistance. - A single-node tree returns
[1]for any query on that node (the only segment is the node itself). - Duplicate query values are fine; they all read from the pre-computed
node_answersarray. - An empty
querieslist returns[]forpalindrome_counts.
Full Solution
from typing import List, Dict
def solve_two_problems(
grid: List[str],
sig: List[int],
n: int,
letters: List[str],
edge_from: List[int],
edge_to: List[int],
queries: List[int],
) -> Dict[str, List]:
# ── Part 1: clearance signatures ──────────────────────────────────────────
robot_locations = []
rows = len(grid)
cols = len(grid[0]) if rows else 0
if rows and cols:
left = [[None] * cols for _ in range(rows)]
right = [[None] * cols for _ in range(rows)]
up = [[None] * cols for _ in range(rows)]
down = [[None] * cols for _ in range(rows)]
for r in range(rows):
last = None
for c in range(cols):
if grid[r][c] == '#':
last = c
elif last is not None:
left[r][c] = c - last
last = None
for c in range(cols - 1, -1, -1):
if grid[r][c] == '#':
last = c
elif last is not None:
right[r][c] = last - c
for c in range(cols):
last = None
for r in range(rows):
if grid[r][c] == '#':
last = r
elif last is not None:
up[r][c] = r - last
last = None
for r in range(rows - 1, -1, -1):
if grid[r][c] == '#':
last = r
elif last is not None:
down[r][c] = last - r
for r in range(rows):
for c in range(cols):
if grid[r][c] != '#':
if [left[r][c], up[r][c], right[r][c], down[r][c]] == sig:
robot_locations.append([r, c])
# ── Part 2: palindrome-capable ancestor segments ───────────────────────────
graph = [[] for _ in range(n)]
for a, b in zip(edge_from, edge_to):
graph[a].append(b)
graph[b].append(a)
node_answers = [0] * n
counts = {0: 1}
stack = [(0, -1, 0, False)]
while stack:
node, parent, parent_mask, exiting = stack.pop()
if exiting:
counts[parent_mask] -= 1
if counts[parent_mask] == 0:
del counts[parent_mask]
continue
mask = parent_mask ^ (1 << (ord(letters[node]) - ord('a')))
valid = counts.get(mask, 0)
for bit in range(26):
valid += counts.get(mask ^ (1 << bit), 0)
node_answers[node] = valid
counts[mask] = counts.get(mask, 0) + 1
stack.append((node, parent, mask, True))
for neighbor in reversed(graph[node]):
if neighbor != parent:
stack.append((neighbor, node, mask, False))
return {
'robot_locations': robot_locations,
'palindrome_counts': [node_answers[q] for q in queries],
}