Constant-space, in-place, fast, iterative solution with early-termination optimization
Intuition\nThe problem statement doesn\'t state that the input array must remain untouched, so we can perform operations in-place on the array to save memory. A
# Intuition\nThe problem statement doesn\'t state that the input array must remain untouched, so we can perform operations in-place on the array to save memory. Additionally, solving things iteratively saves us from adding *n* recursive function calls to the stack, resulting in O(1) space.\n\n# Approach\nIterate over the array a max of *n* times, flattening one-level of arrays each pass until there are no longer any sub-arrays, or we\'ve done the specified number of passes. \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n/**\n * @param {any[]} arr\n * @param {number} depth\n * @return {any[]}\n */\nvar flat = function (arr, n) {\n    // Loop n times, flattening one-level at a time\n    for (let k = n; k > 0; k--) {\n        let alreadyFlat = true;\n        for (let i = 0; i < arr.length; i++) {\n            if (Array.isArray(arr[i])) {\n                let sal = arr[i].length;\n                arr.splice(i, 1, ...arr[i]);\n                // Skip to the end of the elements we just added\n                i += sal - 1;\n                alreadyFlat = false;\n            }\n        }\n        // If the array is already flat, we can return early\n        if (alreadyFlat) return arr; \n    }\n    return arr;\n};\n```
['JavaScript']