
Problem
Solution
Submissions
Flatten Deeply Nested Array
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript function to flatten a deeply nested array without using any built-in methods like Array.flat() or Array.concat(). The function should take a nested array of any depth and return a single-dimensional array containing all elements in their original order.
Example 1
- Input: arr = [1, [2, 3], [4, [5, 6]], 7]
- Output: [1, 2, 3, 4, 5, 6, 7]
- Explanation:
- The input array contains nested arrays at different levels.
- We traverse through each element and check if it's an array.
- If an element is an array, we recursively flatten it.
- All elements are collected in a single flat array.
- The result maintains the original order of elements.
- The input array contains nested arrays at different levels.
Example 2
- Input: arr = [[[1, 2]], [3, [4, [5]]]]
- Output: [1, 2, 3, 4, 5]
- Explanation:
- The input has multiple levels of nesting.
- We recursively process each nested array.
- Elements 1 and 2 are extracted from the triple-nested array.
- Elements 3, 4, and 5 are extracted from their respective nested positions.
- All elements are combined into a single flat array.
- The input has multiple levels of nesting.
Constraints
- The array can contain any type of elements (numbers, strings, objects, etc.)
- The nesting depth can be arbitrary
- You cannot use built-in flattening methods like Array.flat(), Array.concat()
- Time Complexity: O(n) where n is the total number of elements
- Space Complexity: O(d) where d is the maximum depth of nesting
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use recursion to handle nested arrays at any depth
- Check if each element is an array using Array.isArray()
- If the element is an array, recursively call the flatten function
- If the element is not an array, add it directly to the result
- Use the spread operator or push method to combine results