KatInterview

Flatten and Iterate a Nested Registry

Data Structure DesignAuto-graded · 19 test cases
EasyAuto-gradedData Structure Designdata structuresiterationrecursion

Last updated

Tests the ability to implement a depth-first iterator over arbitrarily nested lists and dicts that yields leaf values in traversal order.

Flatten a Nested Registry

A configuration registry stores values in a deeply nested structure built from two container types:

  • Lists – ordered sequences; iterate elements left to right.
  • Dicts – string-keyed mappings; iterate keys in sorted (lexicographic) order.

A leaf is any value that is neither a list nor a dict (it may be an int, float, str, bool, or None).

Write a function that accepts such a nested structure (which is itself either a list, dict, or a leaf) and returns a flat list of all leaf values encountered in a depth-first traversal.

Traversal rules

  1. If the current node is a list, visit each element in index order (0, 1, 2, …).
  2. If the current node is a dict, visit each value in ascending sorted order of its keys.
  3. If the current node is a leaf, emit it.

Constraints

  • The structure may be nested up to 50 levels deep.
  • A single structure may contain up to 2 000 leaf values.
  • Dict keys are non-empty strings.
  • Leaf values may be any JSON-compatible scalar: int, float, str, bool, or None.
  • An empty list [] or empty dict {} contributes zero leaves.
  • The top-level input is guaranteed to be a list, dict, or scalar leaf.

Examples

Example 1

Input: flatten_registry({'b': 2, 'a': 1})

Output: [1, 2]

Example 2

Input: flatten_registry([1, [2, 3], [4, [5]]])

Output: [1, 2, 3, 4, 5]

Example 3

Input: flatten_registry({'z': [10, {'m': 20, 'a': 30}], 'a': 99})

Output: [99, 10, 30, 20]

Hints

Hint 1

Think recursively: handle lists, dicts, and leaves as three separate cases in one function.

Hint 2

For dicts, remember to sort the keys before recursing into their values — the order matters for correctness.

Hint 3

You can use an isinstance check to distinguish containers from leaves; bool is a subclass of int in Python, but since you emit it as-is you don't need to special-case it.