878830. Generating All Subarrays

Easy

Generating All Subarrays

Slug: generating-all-subarrays Difficulty: Easy Id: 878830

Summary

The problem involves generating all possible subarrays from a given array. This requires understanding how to iterate through the original array and construct subarrays by selecting elements from it.

Detailed Explanation

To generate all possible subarrays, we can use two nested loops. The outer loop iterates over each element in the array, while the inner loop selects the start index for the subarray. We then calculate the end index of the subarray by adding 1 to the current start index.

Here's a step-by-step breakdown:

  1. Initialize an empty list subarrays to store all generated subarrays.
  2. Iterate over each element in the array using the outer loop (variable i).
  3. For each iteration, initialize the start index of the subarray to 0 (variable start).
  4. Use the inner loop to select the end index of the subarray by iterating from start up to and including i.
  5. Calculate the end index by adding 1 to start. This ensures that each subarray includes the current element.
  6. Construct the subarray by slicing the original array from the start index to the end index, inclusive (using Python's list slicing syntax).
  7. Append the constructed subarray to the subarrays list.
  8. Repeat steps 3-7 for all elements in the array.

Time complexity: O(n^2), where n is the length of the original array. This is because we have a nested loop structure, with the outer loop running n times and the inner loop also running up to n times.

Space complexity: O(n^2), as we store all generated subarrays in the subarrays list, which has a maximum size of n^2.

Optimized Solutions

Java

java
import java.util.*;

public class Main {
    public static List<int[]> generateSubarrays(int[] arr) {
        List<int[]> subarrays = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            int start = 0;
            for (int j = i; j >= 0; j--) {
                int end = start + 1;
                subarrays.add(Arrays.copyOfRange(arr, start, end));
                start++;
            }
        }
        return subarrays;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        List<int[]> subarrays = generateSubarrays(arr);
        for (int[] subarray : subarrays) {
            System.out.println(Arrays.toString(subarray));
        }
    }
}

Python

View on GeeksforGeeks

Not available

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.