← 返回 xai 的题目列表Unflatten: Refill a Nested Template Structure with Values from a Flat List
类型:online_judge
Problem: Unflatten a Nested Template Structure
Given a flat list of integers and a nested template structure, refill the template’s leaf integer positions in order to produce a new object with the same “shape”.
Input
flat_list: a list of integers of length N.
structure: a nested template object composed of list / tuple / dict.
Constraint: all leaf nodes in the template are integers (their values are placeholders only).
Output
Return a new object new_structure such that:
Container types match the template at every position (list stays list, tuple stays tuple, dict stays dict).
Each leaf integer is replaced by the next value from flat_list in traversal order.
Traversal / Ordering Rules
For list / tuple: left-to-right element order.
For dict: follow the dictionary’s key iteration order (Python dict iteration order).
Error Handling
If flat_list has fewer values than required by the template: raise an error.
If flat_list has more values than required: raise an error.
Example
Given:
flat_list = [6, 7, 8, 9, 0]
structure = {'a': [1, 2, 3], 'b': {'c': [{'d': 4}], 'e': 5}}
Output:
{'a': [6, 7, 8], 'b': {'c': [{'d': 9}], 'e': 0}}
Constraints
Number of leaf integers N: 1 ≤ N ≤ 2 * 10^5
Nesting depth D: 1 ≤ D ≤ 10^4
Requirements
O(N) time.
Preserve the template structure; do not mutate the input template unless explicitly stated.
Example
Input
[6,7,8,9,0]
{'a': [1, 2, 3], 'b': {'c': [{'d': 4}], 'e': 5}}
Output
{'a': [6, 7, 8], 'b': {'c': [{'d': 9}], 'e': 0}}