Nested Array Generator Problem
Description
LeetCode Problem 2649.
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.
Example 1:
Input: arr = [[[6]],[1,3],[]]
Output: [6,1,3]
Explanation:
const generator = inorderTraversal(arr);
generator.next().value; // 6
generator.next().value; // 1
generator.next().value; // 3
generator.next().done; // true
Example 2:
Input: arr = []
Output: []
Explanation: There are no integers so the generator doesn't yield anything.
Constraints:
0 <= arr.flat().length <= 10^50 <= arr.flat()[i] <= 10^5maxNestingDepth <= 10^5
Can you solve this without creating a new flattened version of the array?
Solution
Approach: Iterator stack
Recursion with yield* is the obvious route, but the nesting depth can reach 105, which can overflow the call stack, and it is nicer not to build a flattened copy either. Use an explicit stack of array iterators instead.
Start with the iterator of the input array. Repeatedly ask the iterator on top of the stack for its next item: if it is exhausted, pop it; if the item is an array, push that array's iterator (we dive in and resume the parent later); otherwise it is an integer, so yield it. The traversal order is the required left-to-right depth-first order, empty arrays are skipped naturally, and the generator is lazy: it only advances as far as needed for each next().
Complexity: O(total elements and arrays) time overall; O(d) space for nesting depth d.
/**
* @param {Array} arr
* @return {Generator}
*/
var inorderTraversal = function* (arr) {
const stack = [arr[Symbol.iterator]()];
while (stack.length > 0) {
const { value, done } = stack[stack.length - 1].next();
if (done) {
stack.pop();
} else if (Array.isArray(value)) {
stack.push(value[Symbol.iterator]());
} else {
yield value;
}
}
};
/**
* const gen = inorderTraversal([1, [2, 3]]);
* gen.next().value // 1
* gen.next().value // 2
* gen.next().value // 3
*/