KatInterview

Collect Every Value Stored Under a Key in Nested Data

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsrecursiondfsjson

Last updated

Walk a nested structure of dicts and lists depth-first and gather every value stored under a given key, in traversal order, including matches inside already-matched values.

Gather Values by Key in a Nested Document

You are given a document built from JSON-style data. It may contain dictionaries (string keys), lists, and primitive values (str, int, float, bool, None), nested in any combination and to any depth.

Write a function that returns every value stored under a given key anywhere in the document.

Rules

  • Whenever a dictionary has an entry whose key equals target_key, add that entry's value to the result.
  • A value that was added must still be searched. If it is a dictionary or list, look inside it for more occurrences of target_key.
  • Lists have no keys. Visit their elements from first to last. A string element that happens to equal target_key is not a match, because only dictionary keys count.
  • The result must follow pre-order depth-first order:
    • Go through a dictionary's entries in their stored (insertion) order.
    • When an entry matches, record its value before exploring inside that value.
    • Fully finish one entry's subtree before moving to the next entry.
  • Key comparison is case-sensitive and exact.
  • Every occurrence counts, so equal values found in different places each appear in the result.
  • Values such as None, {}, [], 0, False and "" are ordinary values and must be included when they sit under a matching key.
  • If the key never appears (including when the root is a primitive, an empty dict, or an empty list), return an empty list.
  • Matched values may be returned as references to the original objects; no copying is needed.

Constraints

  • The document contains only dict, list, str, int, float, bool, and None.
  • Dictionary keys are strings.
  • Nesting depth is at most 500.
  • The total number of dictionary entries and list elements is at most 10^5.

Examples

Example 1

Input: collect_values_for_key({'user': {'id': 101, 'name': 'Alice', 'metadata': {'id': 'sub_101', 'status': 'active'}}, 'tags': ['admin', 'staff'], 'id': 999}, 'id')

Output: [101, 'sub_101', 999]

Example 2

Input: collect_values_for_key({'item': 'top-level'}, 'item')

Output: ['top-level']

Hints

Hint 1

Treat the document as a tree: dictionaries and lists are internal nodes, primitives are leaves where recursion stops.

Hint 2

For each dictionary entry, first check whether the key matches and record the value, then recurse into that value whether or not it matched.

Hint 3

Use a single shared result list that you append to during the traversal, and test for matches with key equality rather than truthiness so that None, 0, and empty containers are kept.