KatInterview

Recursive Region Tree and Safe Graph Nodes

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsrecursiongraphsdivide-and-conquer

Last 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

  • N is a power of 2, where 1 ≤ 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.