Challenge - 5 Problems
Bitmask Subsets Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of subsets generated by bitmask
What is the output of the following Rust code that generates all subsets of [1, 2] using bitmask?
DSA Rust
fn main() {
let nums = vec![1, 2];
let n = nums.len();
for mask in 0..(1 << n) {
let mut subset = Vec::new();
for i in 0..n {
if (mask & (1 << i)) != 0 {
subset.push(nums[i]);
}
}
println!("{:?}", subset);
}
}Attempts:
2 left
💡 Hint
Think about how bitmask from 0 to 2^n - 1 represents subsets.
✗ Incorrect
The bitmask runs from 0 to 3 (2^2 - 1). 0 means empty subset, 1 means include first element, 2 means include second element, 3 means include both.
❓ Predict Output
intermediateNumber of subsets generated by bitmask
How many subsets will be generated by the bitmask approach for a vector of length 4?
DSA Rust
fn main() {
let nums = vec![10, 20, 30, 40];
let n = nums.len();
let mut count = 0;
for mask in 0..(1 << n) {
count += 1;
}
println!("{}", count);
}Attempts:
2 left
💡 Hint
Number of subsets of a set with n elements is 2^n.
✗ Incorrect
For n=4, total subsets = 2^4 = 16.
🔧 Debug
advancedIdentify the error in subset generation code
What error will this Rust code produce when generating subsets using bitmask?
DSA Rust
fn main() {
let nums = vec![1, 2, 3];
let n = nums.len();
for mask in 0..(1 << n) {
let mut subset = Vec::new();
for i in 1..n {
if (mask & (1 << i)) != 0 {
subset.push(nums[i]);
}
}
println!("{:?}", subset);
}
}Attempts:
2 left
💡 Hint
Check the inner loop range and which elements are included.
✗ Incorrect
The inner loop starts from 1, so element at index 0 is never included in any subset.
❓ Predict Output
advancedOutput of subsets with reversed bitmask order
What is the output of this Rust code that generates subsets of [5, 10] but iterates bitmask in reverse?
DSA Rust
fn main() {
let nums = vec![5, 10];
let n = nums.len();
for mask in (0..(1 << n)).rev() {
let mut subset = Vec::new();
for i in 0..n {
if (mask & (1 << i)) != 0 {
subset.push(nums[i]);
}
}
println!("{:?}", subset);
}
}Attempts:
2 left
💡 Hint
Reverse iteration prints subsets from full set to empty.
✗ Incorrect
Bitmask runs from 3 down to 0, so subsets print in reverse order.
🧠 Conceptual
expertMaximum subsets generated for n=20 using bitmask
What is the maximum number of subsets generated by bitmask for a vector of length 20?
Attempts:
2 left
💡 Hint
Recall that subsets count is 2^n.
✗ Incorrect
2^20 = 1,048,576 subsets.
