We iterate through each element. If the element is a list, we recursively flatten it; otherwise, we append the integer to our result.
- Initialize an empty result list.
- Iterate through each element in the nested list.
- If the element is a list, extend the result with the recursive flatten call.
- If the element is an integer, append it directly.
- Return the result.
- Time Complexity: O(N), where N is the total number of integers.
- Space Complexity: O(D), where D is the maximum nesting depth.
def flatten(nested_list):
result = []
for item in nested_list:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result