Nested Array Generator - Problem

Given a multi-dimensional array of integers, return a generator object which yields integers in the same order as inorder traversal.

A multi-dimensional array is a recursive data structure that contains both integers and other multi-dimensional arrays.

Inorder traversal iterates over each array from left to right, yielding any integers it encounters or applying inorder traversal to any arrays it encounters.

Input & Output

Example 1 — Simple Nested Array
$ Input: arr = [1,[2,3],4]
Output: [1,2,3,4]
💡 Note: First yield 1, then traverse [2,3] yielding 2 then 3, finally yield 4
Example 2 — Deeply Nested
$ Input: arr = [1,[2,[3,4]],5]
Output: [1,2,3,4,5]
💡 Note: Traverse left-to-right: yield 1, enter [2,[3,4]], yield 2, enter [3,4], yield 3,4, then yield 5
Example 3 — Empty Nested Arrays
$ Input: arr = [1,[],2,[3,[]]]
Output: [1,2,3]
💡 Note: Empty arrays [] are skipped, yielding only the integers 1, 2, and 3

Constraints

  • 1 ≤ arr.length ≤ 500
  • 0 ≤ arr[i] ≤ 1000 or arr[i] is a valid multi-dimensional array
  • The depth of nesting will not exceed 100

Visualization

Tap to expand
Nested Array Generator INPUT arr = [1, [2, 3], 4] Array Structure: [ , , ] 1 [2, 3] 4 Multi-dimensional array with nested elements Depth: 2 levels ALGORITHM STEPS 1 Create Generator Define recursive function 2 Iterate Elements Loop through array items 3 Check Type Is it array or integer? 4 Yield or Recurse yield int / recurse array Element Int? Yes yield No recurse FINAL RESULT Generator Yields: 1 2 3 4 Collected Output: [1, 2, 3, 4] Inorder Traversal: 1. Visit arr[0] = 1 OK 2. Visit arr[1] = [2,3] OK 2a. yield 2, 2b. yield 3 3. Visit arr[2] = 4 OK Key Insight: The recursive generator uses yield* (yield delegation) to flatten nested arrays lazily. When encountering an array, it recursively yields from a new generator instance, preserving left-to-right order while avoiding memory overhead of full array creation. TutorialsPoint - Nested Array Generator | Recursive Generator Approach
Asked in
Google 25 Facebook 18 Amazon 15
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen