Start learning free

LESSON 356 OF 635 · RECURSION

Flatten a Nested List in Java

Practice O(n)

You get a nested list nested. Each item in it is a whole number or another list. Those inner lists hold numbers and lists too.

Return all the numbers in one flat list. Keep them in the order they appear.

The starter code shows how Java holds the items.

 

Example 1:

Input: nested = [7,[-2,[5]],[],4]
Output: [7,-2,5,4]
Explanation: The 7 comes first.
The list [-2,[5]] gives -2, then 5.
The empty list [] gives nothing.
The 4 comes last.

Example 2:

Input: nested = [[[]],[9,9],[]]
Output: [9,9]
Explanation: Only the list [9,9] holds numbers.
Both 9s stay.

Example 3:

Input: nested = [[[[12]]]]
Output: [12]
Explanation: The 12 sits inside four lists.

 

Constraints:

  • 0 to 10,000 numbers in all.
  • At most 10,000 lists, the outer one included.
  • Lists nest at most 50 deep, the outer one included.
  • Each number is a whole number from -100,000 to 100,000.
Note:

Your solution should run in O(n) time, where n counts the numbers and the lists.



Go through the items from left to right. A number goes straight to the end of the answer.

An item that is a list is the same problem, only smaller. Flatten it with the same function, adding its numbers to the same answer. Then go on with the next item.

Each number and each list is visited once, so the time is O(n).
Besides the answer, the recursion uses one call per level of nesting: O(d) extra space for d levels.
STEP 1 OF 7
    Ctrl + Enter to check

    Flatten Nested List in Java

    Keep going with Java500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free