Skip to content

Practice Flatten Deeply Nested Array

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#2625
LeetCode Problem

Flatten Deeply Nested Array

Problem Statement

Given nested array arr and nonnegative depth n, remove up to n levels of nested arrays while retaining element order. Array elements are integers or arrays. At n = 0, preserve all nesting. Implement the operation without Array.flat. Practice approach: Traverse elements with their remaining flatten depth. When an element is an array and depth is positive, visit its contents with depth minus one; otherwise append it unchanged. An explicit stack avoids recursion overflow at depth 1000. Reverse-push children when using a stack so output order remains unchanged. Test empty nested arrays and partial flattening.

Source: Flatten Deeply Nested Array on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
arr = [1,[2,[3]],[],4], n = 1
Output
[1,2,[3],4]
Explanation

One nesting layer is removed; the inner array [3] remains intact.

Constraints

At most 10^5 integers and 10^5 subarrays.
Maximum nesting depth is 1000.
-1000 <= each integer <= 1000
0 <= n <= 1000

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.