Monday, January 31, 2022

Print all subsets

- - -

- - 3

- 2 -

- 2 3

1 - -

1 - 3

1 2 -

1 2 3


package jan20;

public class AllSubsetArray {
public static void main(String[] args) {

// TC: O(1), SC: O(1)
char[] arr = {'a', 'b', 'c'}; // Input array of length n = 3

// TC: O(1), SC: O(1)
int limit = (int) Math.pow(2, arr.length); // Total subsets = 2^n

// TC: Outer loop runs 2^n times => O(2^n), SC: O(1)
for (int i = 0; i < limit; i++) {

// TC: O(1), SC: O(n) — ans string can grow up to length n
String ans = "";

// TC: O(1), SC: O(1)
int temp = i;

// TC: Inner loop runs n times => O(n), SC: O(1)
for (int j = arr.length - 1; j >= 0; j--) {

// TC: O(1), SC: O(1)
int remainder = temp % 2;

// TC: O(1), SC: O(1)
temp = temp / 2;

// TC: O(1) string concat, SC: O(n) over all iterations
if (remainder == 0)
ans = "- " + ans;
else
ans = arr[j] + " " + ans;
}

// TC: O(1), SC: O(1)
System.out.println(ans); // Print one subset
}
}
}


📊 Complexity Table

CaseTime ComplexitySpace ComplexityExplanation
BestO(2ⁿ × n)O(n)Even in best case, the outer loop runs 2ⁿ times, and inner loop n times.
AverageO(2ⁿ × n)O(n)Same work regardless of actual input content.
WorstO(2ⁿ × n)O(n)Full 2ⁿ iterations with O(n) string operations in each.

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:...