Flatten Arrays

• Implement Flatten Arrays. Given an array that may contain nested arrays, give a single resultant array.

function flatten(input){
}

Example:

Input: var input = [2, 1, [3, [4, 5], 6], 7, [8]];
flatten(input);
Output: [2, 1, 3, 4, 5, 6, 7, 8]

• function flatten(input) {

``````var index = input.length - 1;

while (index >= 0) {
if (Array.isArray(input[index])) {
var v = input[index];
input.splice(index, 1);
for (var i in v) {
input.splice(index, 0, v[i]);
index++
}
}
index--;
}

return input;
``````

}

• ``````public static List<Integer> flatten(List<NestedList> l) {
List<Integer> main = new ArrayList<Integer>();
Stack<List<NestedList>> stack = new Stack<List<NestedList>>();
Stack<Integer> indexes = new Stack<Integer>();
while (true) {
if (stack.isEmpty())
break;
int index1 = indexes.pop();
l = stack.pop();
for (int i = index1; i < l.size(); i++) {
NestedList n = l.get(i);
if (n.isInteger()) {
} else {
l = n.list;
break;

}
}
}

return main;
}
``````

• Solution in python

``````def flatten(array, result):
for i in array:
if type(i) == type([]):
flatten(i, result)
else:
result.append(i)
return result
``````

...

flatten([2, 1, [3, [4, 5], 6], [7], 8], [])
[2, 1, 3, 4, 5, 6, 7, 8]

• Java DFS:

``````public void flattenRecursive(List<Object> nestedList) {
List<Object> res = new ArrayList<>();
dfs(nestedList, res);
System.out.println(res);
}

private void dfs(List<Object> nestedList, List<Object> res) {
for(Object e : nestedList) {
if (e instanceof List<?>) dfs((List<Object>) e, res);