KatInterview

Extract String Leaf Paths from Nested JSON Structure

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphstree-traversaliterationstack

Last updated

Traverse nested dictionaries and lists to collect dot-and-bracket paths to all string values, returned in sorted order.

Extract String Leaf Paths from Nested JSON Structure

You need to traverse a complex JSON-like data structure composed of dictionaries, lists, and primitive values, and collect the full path to every string value. The structure may be arbitrarily nested, and your solution must use an iterative approach.

Path Notation Rules

  • Dictionary keys are joined with a dot separator. For example, accessing data["user"]["email"] produces the path user.email.
  • List indices are enclosed in square brackets. For example, accessing data["items"][2] produces the path items[2].
  • Root-level lists begin immediately with bracket notation, such as [0].field.
  • Adjacent list nesting chains brackets without separators: matrix[1][3].
  • Objects inside lists attach the key with a dot after the closing bracket: records[5].status.

Value Filtering

Only include paths that terminate at a string value. Exclude paths leading to:

  • Other primitive types: integers, floats, booleans, or None
  • Empty or non-empty containers (dictionaries or lists)

Output Requirements

Return all qualifying paths in lexicographical (alphabetical) order. Use Python's default string comparison.

Implementation Constraint

Design your traversal using an iterative approach with an explicit stack or queue. Do not use recursion.

Function Signature

def extract_string_paths(data: Any) -> list[str]:
    pass

Constraints

  • Total nodes in the structure: ≤ 10,000
  • Maximum nesting depth: ≤ 100
  • Dictionary keys are alphanumeric strings without spaces, dots, or brackets
  • String values (leaves) may be empty ("")
  • The root may be a dictionary, list, string, or any other type

Examples

Example 1

Input: extract_string_paths({'user': {'name': 'Alice', 'age': 30, 'tags': ['admin', 'dev'], 'profile': {'bio': 'Engineer'}}})

Output: ['user.name', 'user.profile.bio', 'user.tags[0]', 'user.tags[1]']

Example 2

Input: extract_string_paths([{'title': 'Root', 'metadata': None}, {'items': [['leaf1'], 42]}])

Output: ['[0].title', '[1].items[0][0]']

Example 3

Input: extract_string_paths({'a': ['', {'b': 'x'}], 'z': False})

Output: ['a[0]', 'a[1].b']

Example 4

Input: extract_string_paths(['root', {'x': ['nested', {'y': 'deep'}]}, [1, 'last']])

Output: ['[0]', '[1].x[0]', '[1].x[1].y', '[2][1]']

Hints

Hint 1

Use a stack to store (current_value, path_so_far) pairs and process nodes iteratively

Hint 2

When you encounter a dictionary, append each key using dot notation; when you encounter a list, append indices using bracket notation

Hint 3

Only record the path when you pop a string value from the stack; ignore all other primitive types and empty containers