0
0
DSA Pythonprogramming~20 mins

Subsets Generation Using Bitmask in DSA Python - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Bitmask Subsets Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of subsets generated by bitmask
What is the output of the following code that generates all subsets of [1, 2] using bitmask?
DSA Python
nums = [1, 2]
subsets = []
n = len(nums)
for mask in range(1 << n):
    subset = []
    for i in range(n):
        if mask & (1 << i):
            subset.append(nums[i])
    subsets.append(subset)
print(subsets)
A[[], [1], [2], [1, 2]]
B[[], [2], [1], [2, 1]]
C[[1], [2], [1, 2], []]
D[[1, 2], [1], [2], []]
Attempts:
2 left
💡 Hint
Think about how bitmask represents inclusion of elements in subsets.
Predict Output
intermediate
1:00remaining
Number of subsets generated by bitmask
How many subsets will be generated by the bitmask approach for a list of 4 elements?
DSA Python
nums = [10, 20, 30, 40]
n = len(nums)
count = 0
for mask in range(1 << n):
    count += 1
print(count)
A16
B8
C4
D32
Attempts:
2 left
💡 Hint
Number of subsets of a set with n elements is 2^n.
🔧 Debug
advanced
2:00remaining
Identify the error in bitmask subset generation
What error will this code produce when generating subsets using bitmask?
DSA Python
nums = [1, 2, 3]
n = len(nums)
subsets = []
for mask in range(1 << n):
    subset = []
    for i in range(n):
        if mask & i:
            subset.append(nums[i])
    subsets.append(subset)
print(subsets)
ATypeError
BWrong output subsets
CNo error, correct output
DSyntaxError
Attempts:
2 left
💡 Hint
Check the condition mask & i carefully.
🧠 Conceptual
advanced
1:30remaining
Understanding bitmask subset generation order
In what order are subsets generated by bitmask from 0 to 2^n - 1?
ASubsets are generated randomly
BSubsets are generated in lexicographical order of elements
CSubsets are generated in order of bitmask integer value from 0 to 2^n - 1
DSubsets are generated in increasing order of subset size
Attempts:
2 left
💡 Hint
Think about how the loop runs from 0 to 2^n - 1.
Predict Output
expert
3:00remaining
Find subset with maximum sum using bitmask
Given nums = [3, 1, 4, 2], which subset generated by bitmask has the maximum sum less than or equal to 6?
DSA Python
nums = [3, 1, 4, 2]
max_sum = 0
best_subset = []
n = len(nums)
for mask in range(1 << n):
    subset = []
    total = 0
    for i in range(n):
        if mask & (1 << i):
            subset.append(nums[i])
            total += nums[i]
    if total <= 6 and total > max_sum:
        max_sum = total
        best_subset = subset
print(best_subset)
A[1, 4, 2]
B[4, 2]
C[3, 4]
D[3, 1, 2]
Attempts:
2 left
💡 Hint
Check sums of subsets and find the largest sum <= 6. Note the update condition is strict greater than.