This post is completed by 1 user

  • 0
Add to List
Medium

253. Print all subarrays of a given array

Problem: Given an array write an algorithm to print all the possible sub-arrays.

Example:

int [] a = {1, 2, 3};

Output: Possible subarrays –
{1}, {2}, {3}, {1, 2} , {2, 3}, {1, 2, 3}

Approach:

Click here to read about the recursive solution - Print all subarrays using recursion

  1. Use three nested loops.
  2. Outer loops will decide the starting point of a sub-array, call it as startPoint.
  3. First inner loops will decide the group size (sub-array size). Group size starting from 1 and goes up array size. Let's call is as grps.
  4. The most inner loop will actually print the sub-array by iterating the given array from startPoint and print the next grps elements.
  5. See the code below for more understanding.

Output:

1
1 2
1 2 3
1 2 3 4
2
2 3
2 3 4
3
3 4
4