
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.
#include <vector>
using namespace std;
void flattenArrayHelper(vector<int>& result, const vector<int>& arr, int currentDepth, int maxDepth) {
for (const auto &element : arr) {
if (currentDepth < maxDepth && typeid(element) == typeid(vector<int>)) {
flattenArrayHelper(result, element, currentDepth + 1, maxDepth);
} else {
result.push_back(element);
}
}
}
vector<int> flattenArray(const vector<int>& arr, int maxDepth) {
vector<int> result;
flattenArrayHelper(result, arr, 0, maxDepth);
return result;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
vector<int> flattened = flattenArray(arr, 1);
for (int num : flattened) {
cout << num << " ";
}
return 0;
}This C++ solution uses templating to recursively navigate through nested vectors. It flattens the array up to the given depth using a helper function, thereby capturing elements based on comparison to depth threshold. It assumes nested array representations.
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.
1def flatten_array(arr, n):
2 stack = [(arr, 0)]
3 result = []
4
5 while stack:
6 curr, depth = stack.pop()
7 i = 0
8 while i < len(curr):
9 if isinstance(curr[i], list):
10 if depth < n:
11 stack.append((curr, i + 1))
12 stack.append((curr[i], depth + 1))
13 break
14 else:
15 result.extend(curr[i])
16 else:
17 result.append(curr[i])
18 i += 1
19 return result
20
21# Example usage:
22arr = [1, [2, [3, 4], 5], 6, [7, 8]]
23print(flatten_array(arr, 1)) Python’s stack-based solution iterates over the input list using a manual stack. Given tuples holding both the current list and index, flatten_array() evaluates depth to determine their inclusion, breaking into subarrays where appropriate.