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)
}
}
}
}
| Case | Time Complexity | Space Complexity | Explanation |
|---|---|---|---|
| Best Case | O(n³) | O(1) | Even if array is small, still tries all subarrays, 3 nested loops. |
| Average Case | O(n³) | O(1) | Same nested structure always. |
| Worst Case | O(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