
Problem
Solution
Submissions
Flatten a Nested List
Certification: Intermediate Level
Accuracy: 100%
Submissions: 5
Points: 10
Write a Python function to flatten a nested list of integers into a single list.
Example 1
- Input: nested_list = [[1, 2], [3, [4, 5]], 6]
- Output: [1, 2, 3, 4, 5, 6]
- Explanation:
- Step 1: Start with an empty result list.
- Step 2: Process [1, 2]: Add 1 and 2 to the result list. Result = [1, 2].
- Step 3: Process [3, [4, 5]]: Add 3 to the result list. Result = [1, 2, 3].
- Step 4: Process [4, 5]: Add 4 and 5 to the result list. Result = [1, 2, 3, 4, 5].
- Step 5: Process 6: Add 6 to the result list. Result = [1, 2, 3, 4, 5, 6].
- Step 6: Return the flattened list [1, 2, 3, 4, 5, 6].
Example 2
- Input: nested_list = [[1], [2, [3, [4]]]]
- Output: [1, 2, 3, 4]
- Explanation:
- Step 1: Start with an empty result list.
- Step 2: Process [1]: Add 1 to the result list. Result = [1].
- Step 3: Process [2, [3, [4]]]: Add 2 to the result list. Result = [1, 2].
- Step 4: Process [3, [4]]: Add 3 to the result list. Result = [1, 2, 3].
- Step 5: Process [4]: Add 4 to the result list. Result = [1, 2, 3, 4].
- Step 6: Return the flattened list [1, 2, 3, 4].
Constraints
- 1 <= len(nested_list) <= 1000
- Time Complexity: O(n) where n is the total number of elements in the nested list
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use recursion to handle nested lists.
- Iterate through each element, and if it is a list, recursively flatten it.
- Append non-list elements directly to the result.