
Sponsored
Sponsored
The idea behind this approach is to use recursion to flatten the array up to the specified depth n. If the current depth is less than n, we continue flattening; otherwise, we do not flatten further. We leverage recursive calls to process each element and manage the depth level.
Time Complexity: O(m) where m is the total number of elements in the array considering all levels.
Space Complexity: O(m) due to recursive stack space and storage of flattened elements.
using System.Collections.Generic;
class FlattenArray {
public static List<int> Flatten(List<object> arr, int maxDepth) {
List<int> result = new List<int>();
FlattenHelper(arr, maxDepth, 0, result);
return result;
}
private static void FlattenHelper(List<object> arr, int maxDepth, int currentDepth, List<int> result) {
foreach (var element in arr) {
if (element is List<object> sublist) {
if (currentDepth < maxDepth)
FlattenHelper(sublist, maxDepth, currentDepth + 1, result);
else
result.AddRange((List<int>)sublist);
} else {
result.Add((int)element);
}
}
}
static void Main() {
var arr = new List<object> { 1, 2, new List<object> { 3, 4 }, 5 };
var flattened = Flatten(arr, 1);
Console.WriteLine(string.Join(", ", flattened));
}
}This C# solution involves a recursive method FlattenHelper, which processes a nested List structure. It checks objects for List types and regulates depth accordingly. Upon encountering integers, it accumulates them into result, signalling depth compliance.
This technique leverages a stack data structure to simulate recursion iteratively. By using an explicit stack, we can iteratively flatten the array, taking control of the depth level without using the actual recursive calls within the stack frames.
Time Complexity: O(m), iterating through each array element.
Space Complexity: O(m) due to storage in stack elements.
1function flattenArray(arr, maxDepth) {
2 const result = [];
3 const stack = [{ arr, index: 0, depth: 0 }];
4
5 while (stack.length > 0) {
6 const { arr: current, index, depth } = stack.pop();
7
8 if (index < current.length) {
9 if (Array.isArray(current[index]) && depth < maxDepth) {
10 stack.push({ arr: current, index: index + 1, depth });
11 stack.push({ arr: current[index], index: 0, depth: depth + 1 });
12 } else {
13 result.push(current[index]);
14 stack.push({ arr: current, index: index + 1, depth });
15 }
16 }
17 }
18
19 return result;
20}
21
22let arr = [1, [2, [3, 4], 5], 6, [7, 8]];
23console.log(flattenArray(arr, 1));JavaScript facilitates iteration through an explicit stack to track array representations and respective depths. The solution dynamically adjusts stack content based on depth, solidly putting down a path for deep handling without recursion.