2649. Nested Array Generator

Explanation:

To solve this problem without creating a new flattened version of the array, we can implement a generator function that performs an inorder traversal on the multi-dimensional array. We can use a recursive approach to handle nested arrays.

  1. Define a generator function inorderTraversal that takes the multi-dimensional array as input.
  2. Iterate over the array elements, and for each element:
    • If the element is an integer, yield the integer.
    • If the element is an array, recursively call inorderTraversal on the sub-array.
  3. The generator will yield integers in the order they are encountered during the inorder traversal of the multi-dimensional array.

Time Complexity: The time complexity of this approach is O(N), where N is the total number of integers in the multi-dimensional array.

Space Complexity: The space complexity is also O(N) due to the recursion stack.

:

import java.util.Iterator;
import java.util.List;

public class NestedArrayGenerator {
    public static Iterator<Integer> inorderTraversal(List<Object> arr) {
        return new Iterator<Integer>() {
            private Iterator<Object> iterator = arr.iterator();
            private Iterator<Integer> currentIterator = null;

            @Override
            public boolean hasNext() {
                while ((currentIterator == null || !currentIterator.hasNext()) && iterator.hasNext()) {
                    Object obj = iterator.next();
                    if (obj instanceof Integer) {
                        currentIterator = List.of((Integer) obj).iterator();
                    } else if (obj instanceof List) {
                        currentIterator = inorderTraversal((List<Object>) obj);
                    }
                }
                return currentIterator != null && currentIterator.hasNext();
            }

            @Override
            public Integer next() {
                return currentIterator.next();
            }
        };
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.