This post is completed by 1 user
|
Add to List |
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
- Use three nested loops.
- Outer loops will decide the starting point of a sub-array, call it as startPoint.
- 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.
- The most inner loop will actually print the sub-array by iterating the given array from startPoint and print the next grps elements.
- See the code below for more understanding.
public class Main {
public static void printSubArrays(int [] arrA){
int arrSize = arrA.length;
//start point
for (int startPoint = 0; startPoint <arrSize ; startPoint++) {
//group sizes
for (int grps = startPoint; grps <=arrSize ; grps++) {
//if start point = 1 then
//grp size = 1 , print 1
//grp size = 2, print 1 2
//grp size = 3, print 1 2 3 ans so on
for (int j = startPoint ; j < grps ; j++) {
System.out.print(arrA[j] + " ");
}
System.out.println();
}
}
}
public static void main(String[] args) {
int [] arrA = {1,2,3, 4};
printSubArrays(arrA);
}
}
def print_sub_arrays(arr):
arr_size = len(arr)
# start point
for start_point in range(arr_size):
# group sizes
for grps in range(start_point, arr_size + 1):
# if start point = 1 then
# group size = 1, print 1
# group size = 2, print 1 2
# group size = 3, print 1 2 3 and so on
for j in range(start_point, grps):
print(arr[j], end=" ")
print()
if __name__ == "__main__":
arr_a = [1, 2, 3, 4]
print_sub_arrays(arr_a)
package main
import "fmt"
func printSubArrays(arrA []int) {
arrSize := len(arrA)
// Start point
for startPoint := 0; startPoint < arrSize; startPoint++ {
// Group sizes
for grps := startPoint; grps <= arrSize; grps++ {
// If start point = 1 then
// Group size = 1, print 1
// Group size = 2, print 1 2
// Group size = 3, print 1 2 3 and so on
for j := startPoint; j < grps; j++ {
fmt.Print(arrA[j], " ")
}
fmt.Println()
}
}
}
func main() {
arrA := []int{1, 2, 3, 4}
printSubArrays(arrA)
}
Output:
1 1 2 1 2 3 1 2 3 4 2 2 3 2 3 4 3 3 4 4