Sunday, January 30, 2022

Print all subarrays

I/P: {10,20,30} 

O/P: 

10 10 20 10 20 30 20 20 30 30



package jan20;

public class SubArray {
public static void main(String[] args) {
int[] arr = {10, 20, 30}; // O(1) time, O(1) space (static array initialization)

for (int i = 0; i < arr.length; i++) { // Outer loop: O(n)
for (int j = i; j < arr.length; j++) { // Middle loop: O(n)
for (int k = i; k <= j; k++) { // Inner loop: O(n)
System.out.print(arr[k] + " "); // O(1) time (printing element)
}
System.out.println(); // O(1) time (printing new line)
}
}
}
}


CaseTime ComplexitySpace ComplexityExplanation
Best CaseO(n³)O(1)Even if array is small, still tries all subarrays, 3 nested loops.
Average CaseO(n³)O(1)Same nested structure always.
Worst CaseO(n³)O(1)Largest input → all three loops fully expand to n iterations.

1-line Summary:

  • Generating and printing all subarrays takes O(n³) time and O(1) space because of the three nested loops without any extra storage.

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...