2625. Flatten Deeply Nested Array
IntuitionApproachComplexity
Time complexity:- o(m)

Space complexity:- o(m)
Code
# 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:- o(m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:- o(m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Array} arr\n * @param {number} depth\n * @return {Array}\n */\nvar flat = function(arr, n) {\n    let stack = [...arr.map(item => [item, n])]; //Initialize a stack with the elements of the array, each paired with the initial depth.\n    let result = []; //Initialize an empty result array to store the flattened elements.\n\n    while (stack.length > 0) { //while there are elements in the stack.\n        let [current, depth] = stack.pop();  //Pop an element from the stack along with its depth.\n\n        if (Array.isArray(current) && depth > 0) {\n            //If current is an array and depth is greater than 0, push its elements to the stack with the reduced depth.\n            stack.push(...current.map(item => [item, depth - 1]));\n            //If current is not an array or depth is 0, push it to the result array.\n        } else {\n            result.push(current);\n        }\n    }\n\n    // The stack unwinds in LIFO order, so we need to reverse the result to maintain original order\n    return result.reverse();\n};\n\n// Example usage\n// const nestedArray = [1, [2, [3, [4, 5]]], 6];\n// const depth = 2;\n// const flatArray = flat(nestedArray, depth);\n// console.log(flatArray); // Output: [1, 2, 3, [4, 5], 6]\n\n```
['JavaScript']