
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.
1using System;
2using System.Collections;
3using System.Collections.Generic;
4
5class FlattenArray {
6 public static List<int> Flatten(IList arr, int n) {
7 Stack<Tuple<IList, int>> stack = new Stack<Tuple<IList, int>>();
8 List<int> result = new List<int>();
9 stack.Push(new Tuple<IList, int>(arr, 0));
10
11 while (stack.Count > 0) {
12 var (current, depth) = stack.Pop();
13 for (int i = 0; i < current.Count; i++) {
14 if (current[i] is IList sublist) {
15 if (depth < n) {
16 stack.Push(new Tuple<IList, int>(current, i + 1));
17 stack.Push(new Tuple<IList, int>(sublist, depth + 1));
18 break;
19 } else {
20 result.AddRange((IList<int>)sublist);
21 }
22 } else {
23 result.Add((int)current[i]);
24 }
25 }
26 }
27
28 return result;
29 }
30
31 static void Main() {
32 IList arr = new List<object> { 1, 2, new List<object> { 3, 4 }, 5 };
33 var flattened = Flatten(arr, 1);
34 Console.WriteLine(string.Join(", ", flattened));
35 }
36}C# uses a tuple stack as a structure to track depth and indices. It manages the depth of sublists directly through proper conditional retrieval and accumulates results iteratively without recursion overflow concerns.