
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.
In this JavaScript implementation, recursion is used through the helper function flattenHelper. Arrays and depths are managed with the JavaScript Array.isArray() method, allowing differentiation between arrays and base elements. This recursive design ensures depth handling and efficient element retrieval.
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.
1import java.util.*;
2
3public class FlattenArray {
4 private static class Element {
5 List<Object> list;
6 int index;
7 int depth;
8
9 Element(List<Object> list, int depth) {
10 this.list = list;
11 this.index = 0;
12 this.depth = depth;
13 }
14 }
15
16 public static List<Integer> flattenArray(List<Object> arr, int n) {
17 List<Integer> result = new ArrayList<>();
18 Stack<Element> stack = new Stack<>();
19 stack.push(new Element(arr, 0));
20
21 while (!stack.isEmpty()) {
22 Element current = stack.peek();
23 if (current.index >= current.list.size()) {
24 stack.pop();
25 } else {
26 Object item = current.list.get(current.index++);
27 if (item instanceof List) {
28 if (current.depth < n) {
29 stack.push(new Element((List<Object>) item, current.depth + 1));
30 } else {
31 result.addAll((List<Integer>) item);
32 }
33 } else {
34 result.add((Integer) item);
35 }
36 }
37 }
38 return result;
39 }
40
41 public static void main(String[] args) {
42 List<Object> arr = Arrays.asList(1, 2, Arrays.asList(3, 4));
43 List<Integer> flattened = flattenArray(arr, 1);
44 System.out.println(flattened);
45 }
46}Java adaptation works with a stack to iteratively address nested lists. It uses Element class for tracking depth and index, processing array components depth-first based on current settings, mitigating stack overflow risks.