Middle
How to traverse a multi-dimensional array with unknown depth without recursion, using a stack?
sobes.tech AI
Answer from AI
To traverse a multi-dimensional array with unknown depth without recursion, you can use a stack to store the current elements and their indices. The idea is to iterate through the elements; if an element is an array, push it onto the stack for further processing; if it is a value, process it.
Example in JavaScript:
function flattenArray(arr) {
const stack = [...arr]; // copy the original array into the stack
const result = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
// if the element is an array, push its elements onto the stack
stack.push(...next);
} else {
// if the element is a value, add it to the result
result.push(next);
}
}
// since we use a stack (LIFO), the order of elements will be reversed
return result.reverse();
}
const nested = [1, [2, [3, 4], 5], 6];
console.log(flattenArray(nested)); // [1, 2, 3, 4, 5, 6]
Thus, the stack allows traversing the structure without recursion, processing nested arrays sequentially.