Flatten Deeply Nested Arrays

Medium
71
1
42.9% Acceptance

In this lab, you will be tasked to create a function called flat that accepts a deeply nested multi-dimensional array arr and a depth value n. The function must return a flattened version of that array based on the given depth n. The depth at which elements should be flattened depends on the depth value n. The depth of the elements in the first array are considered to be 0. You must solve this problem without using the built-in Array.flat method.

A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.

A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n.

Examples

Example 1:

const arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]; const n = 0; const result = flat(arr, n); console.log(result); // Output: [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]

Explanation: Passing a depth of n=0 will always result in the original array. This is because the smallest possible depth of a subarray (0) is not less than n=0. Thus, no subarray should be flattened.

Example 2:

const arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]; const n = 1; const result = flat(arr, n); console.log(result); // Output: [1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15]

Explanation: The subarrays starting with 4, 7, and 13 are all flattened. This is because their depth of 0 is less than 1. However, [9, 10, 11] remains unflattened because its depth is 1.

Example 3:

const arr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]; const n = 2; const result = flat(arr, n); console.log(result); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Explanation: The maximum depth of any subarray is 1. Thus, all of them are flattened.

Constraints:

  • 0 <= count of numbers in arr <= 105
  • 0 <= count of subarrays in arr <= 105
  • maxDepth <= 1000
  • -1000 <= each number <= 1000
  • 0 <= n <= 1000