arr = [1, [2,3], [[[4]]]]
arr2 = [1, [2,3], [[[4]]], [[[[[[[[[[[[[5]]]]]]]]]]]]]]
How to flatten this list to become:
[1,2,3,4]
[1,2,3,4,5]
In an iterative way and optimal solution?
def flatten(arr):
ans = []
arrcopy = arr[:]
queue = []
while len(arrcopy)>0:
item = arrcopy.pop(0)
if type(item) == list:
arrcopy.extend(item)
else:
ans.append(item)
return ans
Recursive is trivial. I have iterative solution, but pop takes O(n^2) time. Is there a way to make solution more optimal?