Extract String Leaf Paths from Nested JSON Structure
Trees & GraphsAuto-graded · 23 test casesLast 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 pathuser.email. - List indices are enclosed in square brackets. For example, accessing
data["items"][2]produces the pathitems[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
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires walking through a tree-like structure where nodes can be dictionaries (branching by key) or lists (branching by index), and collecting paths only to string leaves.
The core strategy is to use an explicit stack that holds (node, accumulated_path) tuples. Start with the root and an empty path. On each iteration:
- Pop a tuple from the stack
- Check the node type:
- If it's a string, this is a leaf we want—add the path to the result
- If it's a dictionary, push all key-value pairs onto the stack with updated paths
- If it's a list, push all elements with bracket-indexed paths
- For any other type (int, float, bool, None), do nothing—these are filtered out
- Build child paths according to the notation rules:
- For dictionary children: if the parent path is empty (root dict), use just the key; otherwise append
.key - For list children: always append
[index]directly to the parent path
- For dictionary children: if the parent path is empty (root dict), use just the key; otherwise append
- Sort the collected paths at the end to satisfy the lexicographical ordering requirement
Why This Works
Every node in the input structure is visited exactly once because we push all children of each container onto the stack. Since the structure is a tree (no cycles or shared references), each string leaf generates exactly one path. The path construction rules ensure that different leaves produce distinct path strings. Finally, sorting the result makes the output deterministic and independent of dictionary iteration order.
Complexity
- Time: O(N · P + L log L · P), where N is the number of nodes, P is the average path length, and L is the number of string leaves. Building paths involves string concatenation for each node, and sorting involves comparing paths.
- Space: O(D · P + L · P), where D is the maximum depth. The stack holds at most one entry per level of nesting, and the output holds all leaf paths.
Given the constraints (N ≤ 10,000, depth ≤ 100), this solution runs efficiently. Using an iterative approach also avoids Python's recursion depth limit.
Reference Solution
from typing import Any
def extract_string_paths(data: Any) -> list[str]:
result = []
stack = [(data, "")]
while stack:
value, path = stack.pop()
if isinstance(value, str):
result.append(path)
elif isinstance(value, dict):
items = list(value.items())
for key, child in reversed(items):
child_path = str(key) if not path else path + "." + str(key)
stack.append((child, child_path))
elif isinstance(value, list):
for index in range(len(value) - 1, -1, -1):
child_path = path + "[" + str(index) + "]"
stack.append((value[index], child_path))
result.sort()
return result