#2649

Nested Array Generator

Medium
RecursionGenerator Functions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(d)
💡

Intuition

Time O(n)Space O(d)

The optimal solution uses a generator function that recursively yields integers directly from the nested structure without creating an intermediate list. This is efficient in terms of both time and space.

⚙️

Algorithm

4 steps
  1. 1Step 1: Define a generator function that takes the multi-dimensional array as input.
  2. 2Step 2: Iterate through each element of the array.
  3. 3Step 3: If the element is an integer, yield it. If it's an array, recursively call the generator function.
  4. 4Step 4: The generator will yield integers in the same order as they are encountered.
solution.py9 lines
1# Full working Python code
2
3def inorderTraversal(arr):
4    for item in arr:
5        if isinstance(item, int):
6            yield item
7        else:
8            yield from inorderTraversal(item)
9

Complexity note: The time complexity is O(n) because we visit each element exactly once. The space complexity is O(d) where d is the maximum depth of the nested arrays, due to the call stack used in recursion.

  • 1Using generators allows for efficient memory usage, especially with large nested structures.
  • 2Recursive functions can simplify the traversal of nested data structures.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.