Skip to content

Instantly share code, notes, and snippets.

@tivrfoa
Created February 23, 2025 13:42
Show Gist options
  • Save tivrfoa/e51466d3f68473060f7737fb72634fb8 to your computer and use it in GitHub Desktop.
Save tivrfoa/e51466d3f68473060f7737fb72634fb8 to your computer and use it in GitHub Desktop.
Prompting ChatGPT: write a Java interview question where recursion is a good solution

Java Interview Question: Using Recursion to Solve a Problem

Question:

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.

Example Input:

List<Object> nestedList = List.of(1, List.of(2, 3, List.of(4, 5)), 6);

Expected Output:

Sum: 21

Requirements:

  1. Implement a function sumNestedList(List<Object> list) that calculates the sum recursively.
  2. Your function should handle deeply nested lists efficiently.
  3. Do not use loops for iterating over nested lists—use recursion instead.
  4. You may assume that the list contains only integers or other lists.

Follow-up Questions:

  1. Why is recursion a good approach for this problem?
  2. What is the time complexity of your solution?
  3. How would you modify this function to handle an empty list?
  4. 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.


Recursive Implementation

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
    }
}

Explanation:

  1. 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 calls sumHelper on it.
  2. Base Case:

    • When an empty list is encountered, the function naturally returns 0.

Time Complexity Analysis:

  • 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.

Follow-up Enhancements:

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? 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment