We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Flatten Deeply Nested Array

Number: 2759

Difficulty: Medium

Paid? No

Companies: PayPal, Rivian, Meta, Yandex, TikTok


Problem Description

Given a multi-dimensional array arr and a depth n, return a version of the array that is flattened up to that depth. The first level (depth 0) elements should be flattened if they are arrays and if the current depth is less than n. Arrays at a depth equal to or above n should remain intact.


Key Insights

  • Use recursion to traverse the array while tracking the current depth.
  • Flatten an element (i.e. if it is an array) only when the current depth is less than n.
  • If the current depth equals n, push the subarray as is.
  • Ensure that both numbers and nested arrays are handled correctly and maintain order.

Space and Time Complexity

Time Complexity: O(total number of elements) – each element is processed once. Space Complexity: O(total number of elements) – additional space for the output array and recursion stack in the worst case.


Solution

The solution uses a recursive helper function that takes the current array and the current depth. For each element in the array, if it is not an array, it is added directly to the result. If it is an array and the current depth is less than n, the helper function is called recursively with depth incremented by 1 and the returned flattened elements are added to the result. Otherwise, if the element is an array and the current depth is n (or greater), it is simply appended without flattening. This algorithm ensures that arrays are flattened only up to the specified depth, preserving deeper nested arrays intact.


Code Solutions

def flatten_deeply(arr, n):
    # Recursive helper function to flatten the array up to the given depth.
    def helper(current_arr, current_depth):
        result = []
        # Iterate over each element in the current array.
        for elem in current_arr:
            # If element is a list and current depth is less than n, flatten it further.
            if isinstance(elem, list) and current_depth < n:
                result.extend(helper(elem, current_depth + 1))
            else:
                # Otherwise, append the element as is.
                result.append(elem)
        return result

    # Start flattening from depth 0.
    return helper(arr, 0)

# Example usage:
arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
print(flatten_deeply(arr, 1))
← Back to All Questions