![]() |
VOOZH | about |
Given an array arr[], the task is to generate all the possible subarrays of the given array.
Examples:
Input: arr[] = [1, 2, 3]
Output: [ [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] ]
Input: arr[] = [1, 2]
Output: [ [1], [1, 2], [2] ]
To generate a subarray, we need a starting index from the original array. For choosing the starting index, we can run a loop from [0 to n-1] and consider each i as the starting index. For each starting index i, we can select an ending index from the range [i to n-1]. A nested loop from [i to n-1] will help in selecting the ending index. Once we have the starting and ending indices, we need an innermost loop to print the elements in this subarray.
All Non-empty Subarrays 1 1 2 1 2 3 1 2 3 4 2 2 3 2 3 4 3 3 4 4
We use two pointers start and end to maintain the starting and ending point of the array and follow the steps given below:
Below is the implementation of the above approach.
1 1 2 2 1 2 3 2 3 3