Recursive solution
IntuitionApproachComplexity
Time complexity:
O(n), where n is the total number of elements and sub-elements in the array.
Space complexity:
O(n) due to the resu
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n), where n is the total number of elements and sub-elements in the array.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) due to the result array and recursive stack.\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function (arr, n, currentDepth = 0) {\n    let res = []\n    for (const element of arr) {\n        if (Array.isArray(element) && currentDepth < n) {\n            res.push(...flat(element, n, currentDepth + 1));\n        } else {\n            res.push(element);\n        }\n    }\n    return res\n};\n```
['JavaScript']