Recursive Region Tree and Safe Graph Nodes
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests recursive spatial subdivision (quadtree construction) and graph cycle detection (identifying nodes that always terminate).
You must solve two independent problems and return a dictionary containing both results.
Problem 1: Construct a Region Quadtree
Given an N × N grid of integers where N is a power of 2, build a quadtree representation.
Each quadtree node corresponds to a square subregion:
- If all cells in the subregion hold the same value, create a leaf node storing that value
- Otherwise, create an internal node with four children representing:
- top-left quadrant
- top-right quadrant
- bottom-left quadrant
- bottom-right quadrant
Return the quadtree as a nested dictionary where:
- Leaf nodes:
{"leaf": True, "value": <int>} - Internal nodes:
{"leaf": False, "children": [<tl>, <tr>, <bl>, <br>]}
Problem 2: Identify Always-Terminating Graph Nodes
Given a directed graph with nodes 0 to n-1 as an adjacency list graph (where graph[i] lists node i's outgoing edges):
- A terminal node has no outgoing edges
- A safe node is one where every possible path eventually reaches a terminal node (never cycles indefinitely)
Return all safe nodes sorted in ascending order.
Return Format
Return a dictionary with two keys:
"quadtree": the root of the constructed quadtree"safe_nodes": a sorted list of safe node indices
Constraints
Nis a power of 2, where1 ≤ N ≤ 512- Grid values are integers in the range
[-1000, 1000] 0 ≤ n ≤ 10000(number of graph nodes)- Each node has at most 50 outgoing edges
- The graph may contain self-loops and duplicate edges
Examples
Example 1
Input: construct_quadtree_and_safe_nodes([[1, 1], [1, 1]], [[1], [2], []])
Output: {'quadtree': {'leaf': True, 'value': 1}, 'safe_nodes': [0, 1, 2]}
Hints
Hint 1
For the quadtree: use divide-and-conquer recursion. The base case is a 1×1 region. After building four child quadrants, check if they can be merged into a single leaf.
Hint 2
For safe nodes: a node is unsafe if any path from it can reach a cycle. Use reverse topological sort starting from terminal nodes.
Hint 3
Build the reversed graph and track out-degrees. Process nodes with out-degree 0 first, then propagate safety backward through predecessors.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines two classic algorithmic patterns: recursive spatial decomposition and graph cycle detection.
Part 1: Quadtree Construction
We recursively divide each square region into four equal quadrants until we reach 1×1 base cases. The key optimization is bottom-up merging: after constructing all four child quadrants, we check whether they are all leaves with identical values. If so, we merge them into a single leaf rather than keeping an internal node.
For a region starting at position (row, col) with side length size, the four quadrants have side length size/2 and start at:
- Top-left:
(row, col) - Top-right:
(row, col + size/2) - Bottom-left:
(row + size/2, col) - Bottom-right:
(row + size/2, col + size/2)
Why this is correct: By induction on region size. A 1×1 region is trivially uniform. For larger regions, we correctly identify uniformity by checking whether all four child quadrants are uniform with the same value, which happens exactly when all four children are identical leaves.
Time complexity: O(N²). The recurrence T(N²) = 4·T(N²/4) + O(1) resolves to linear in the number of cells, since each cell is processed exactly once.
Space complexity: O(log N) recursion depth plus O(N²) for the output tree in the worst case (e.g., a checkerboard pattern).
Part 2: Safe Node Detection
A node is unsafe if and only if some path from it reaches a cycle. We use reverse topological sort (Kahn's algorithm on the reversed graph):
- Compute each node's out-degree
- Initialize a queue with all terminal nodes (out-degree 0)
- Process nodes from the queue: mark each as safe, then decrement the out-degree of each predecessor in the reversed graph
- When a predecessor's out-degree reaches 0, all its successors are proven safe, so enqueue it
- Nodes that never reach out-degree 0 lie on or can reach a cycle, so they are unsafe
Why this is correct: A node is enqueued only after all its successors are proven safe, guaranteeing every path from it terminates. Conversely, any safe node must eventually be enqueued—otherwise, following never-enqueued successors would build an infinite path, which must contain a cycle in a finite graph, contradicting safety.
Time complexity: O(V + E) to build the reverse graph and process all edges once.
Space complexity: O(V + E) for the reverse adjacency list and degree tracking.
from typing import List, Dict
from collections import deque
def construct_quadtree_and_safe_nodes(image: List[List[int]], graph: List[List[int]]) -> Dict[str, object]:
n = len(image)
def build(row, col, size):
if size == 1:
return {"leaf": True, "value": image[row][col]}
half = size // 2
children = [
build(row, col, half),
build(row, col + half, half),
build(row + half, col, half),
build(row + half, col + half, half),
]
first = children[0]
if first["leaf"]:
val = first["value"]
if all(ch["leaf"] and ch["value"] == val for ch in children):
return {"leaf": True, "value": val}
return {"leaf": False, "children": children}
quadtree = build(0, 0, n) if n else {"leaf": True, "value": None}
num_nodes = len(graph)
out_degree = [len(neighbors) for neighbors in graph]
reverse_graph = [[] for _ in range(num_nodes)]
for node, neighbors in enumerate(graph):
for neighbor in neighbors:
reverse_graph[neighbor].append(node)
queue = deque(node for node, deg in enumerate(out_degree) if deg == 0)
is_safe = [False] * num_nodes
while queue:
node = queue.popleft()
is_safe[node] = True
for pred in reverse_graph[node]:
out_degree[pred] -= 1
if out_degree[pred] == 0:
queue.append(pred)
return {
"quadtree": quadtree,
"safe_nodes": [node for node in range(num_nodes) if is_safe[node]],
}