Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to generate all subsets of an array using bitmask.
DSA C#
for (int mask = 0; mask < (1 << [1]); mask++) { List<int> subset = new List<int>(); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { subset.Add(arr[i]); } } // process subset }
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr.Length directly without storing in n.
Using mask or i in the bit shift instead of n.
✗ Incorrect
The outer loop runs from 0 to 2^n - 1, where n is the number of elements. So we use n to shift 1 by n bits.
2fill in blank
mediumComplete the condition to check if the i-th element is included in the current subset.
DSA C#
if ((mask & (1 << [1])) != 0) { subset.Add(arr[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using mask or n instead of i in the bit shift.
Using arr[i] inside the bit shift.
✗ Incorrect
We check the i-th bit of mask to see if the i-th element is included.
3fill in blank
hardFix the error in the code to correctly generate subsets using bitmask.
DSA C#
int n = arr.Length; for (int mask = 0; mask [1] (1 << n); mask++) { List<int> subset = new List<int>(); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { subset.Add(arr[i]); } } // process subset }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes one extra iteration leading to invalid subsets.
Using '>' or '>=' causes no iterations.
✗ Incorrect
The loop should run while mask is less than 2^n, not less than or equal to, to avoid out of range.
4fill in blank
hardFill both blanks to create a dictionary mapping each subset's bitmask to its sum.
DSA C#
Dictionary<int, int> subsetSums = new Dictionary<int, int>(); for (int mask = 0; mask < (1 << n); mask++) { int sum = 0; for (int i = 0; i < n; i++) { if (mask [1] (1 << i) != 0) { sum [2] arr[i]; } } subsetSums[mask] = sum; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '|' instead of '&' in the condition.
Using '-=' instead of '+=' for sum.
✗ Incorrect
Use '&' to check if the i-th bit is set, and '+=' to add the element to sum.
5fill in blank
hardFill all three blanks to generate all subsets and print them.
DSA C#
int n = arr.Length; for (int [1] = 0; [2] < (1 << n); [3]++) { List<int> subset = new List<int>(); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { subset.Add(arr[i]); } } Console.WriteLine(string.Join(", ", subset)); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing errors.
Using i instead of mask for outer loop.
✗ Incorrect
The outer loop variable is mask, used in initialization, condition, and increment.
