Flatten List

Recursion
https://www.lintcode.com/problem/flatten-list

# Solution

Both solutions take linear time and space.

# Recursion

def flatten(self, nestedList):
    res = []
    def helper(nestedList):
        for item in nestedList:
            if isinstance(item, list):
                helper(item)
            else:
                res.append(item)
    helper(nestedList)
    return res
1
2
3
4
5
6
7
8
9
10

# Iteration w/ Stack

def flatten(self, nestedList):
    stack = [nestedList]
    res = []
    while stack:
        top = stack.pop()
        if isinstance(top, list):
            stack.extend(reversed(top))
        else:
            res.append(top)
    return res
1
2
3
4
5
6
7
8
9
10