You are given a nested list of integers, where each element is either an integer or another list of integers. Implement a function in Java that sums all integers in the nested list, regardless of how deeply nested they are.
List<Object> nestedList = List.of(1, List.of(2, 3, List.of(4, 5)), 6);
Sum: 21
- Implement a function
sumNestedList(List<Object> list)
that calculates the sum recursively. - Your function should handle deeply nested lists efficiently.
- Do not use loops for iterating over nested lists—use recursion instead.
- You may assume that the list contains only integers or other lists.
- Why is recursion a good approach for this problem?
- What is the time complexity of your solution?
- How would you modify this function to handle an empty list?
- How would you optimize this for very deep recursion to avoid
StackOverflowError
?
Would you like a sample implementation? 😊
prompt: yes
Here’s a recursive Java solution to sum all integers in a nested list.
import java.util.*;
public class NestedListSum {
public static int sumNestedList(List<Object> list) {
return sumHelper(list);
}
private static int sumHelper(List<Object> list) {
int sum = 0;
for (Object item : list) {
if (item instanceof Integer) {
sum += (Integer) item; // Add integer values directly
} else if (item instanceof List) {
sum += sumHelper((List<Object>) item); // Recursive call for nested lists
}
}
return sum;
}
public static void main(String[] args) {
List<Object> nestedList = List.of(1, List.of(2, 3, List.of(4, 5)), 6);
System.out.println("Sum: " + sumNestedList(nestedList)); // Expected output: 21
}
}
-
Recursive Function (
sumHelper
)- Loops through each item in the list.
- If the item is an
Integer
, adds it to the sum. - If the item is another
List
, recursively callssumHelper
on it.
-
Base Case:
- When an empty list is encountered, the function naturally returns
0
.
- When an empty list is encountered, the function naturally returns
- O(N), where N is the total number of integers in the nested structure.
- Since we traverse each element once, recursion depth is proportional to the nesting level.
✅ Handle edge cases (e.g., empty lists).
✅ Avoid StackOverflowError for very deep recursion (convert to iterative with a stack).
✅ Support additional data types (e.g., Double
or String
parsing).
Would you like me to optimize this further with an iterative approach? 🚀