We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Nested Array Generator

Number: 2783

Difficulty: Medium

Paid? No

Companies: N/A


Problem Description

Given a multi-dimensional array of integers (which may contain further nested arrays), implement a generator that yields integers in the same order as an inorder traversal (i.e. process the current list from left to right, recursively traversing any nested arrays). The solution must not create a fully flattened copy of the array.


Key Insights

  • Use recursive traversal to process arbitrarily nested arrays.
  • Yield integers immediately when encountered; do not accumulate them in an auxiliary container.
  • Leverage language features such as generator functions (Python, JavaScript) or implement lazy iterators using a stack or coroutines (Java, C++).
  • This approach minimizes extra space usage by avoiding full flattening.

Space and Time Complexity

Time Complexity: O(n), where n is the total number of elements (including nested arrays) since each element is visited exactly once. Space Complexity: O(d), where d is the maximum nesting depth (used by the recursion or stack).


Solution

The solution uses a recursive approach to traverse the nested structure. In languages with native generator support, a recursive generator function is defined to yield each integer as soon as it’s processed. In languages without native generators, we simulate this behavior by implementing an iterator using a stack (or, in C++20, using coroutines). This lazy evaluation avoids creating a new, flattened list and keeps extra space usage to the current recursion/stack depth.


Code Solutions

def inorderTraversal(arr):
    # Recursively iterate over each element in the current array.
    for elem in arr:
        # If the element is an integer, yield it immediately.
        if isinstance(elem, int):
            yield elem
        # If the element is a list (nested array), recursively yield its integers.
        elif isinstance(elem, list):
            yield from inorderTraversal(elem)

# Example usage:
# arr = [[[6]],[1,3],[]]
# generator = inorderTraversal(arr)
# print(next(generator))  # Output: 6
# print(next(generator))  # Output: 1
# print(next(generator))  # Output: 3
← Back to All Questions