Practice
isPowerOfFour(16)?Solution
Step 1: Calculate log2(16)
log2(16) = 4, dividing by 2 gives 2.0.Step 2: Check if 2.0 equals int(2.0)
2.0 == 2 is True, so the function returns True.Final Answer:
Option A -> Option AQuick Check:
16 is 4^2, so output True is expected [OK]
- Assuming floating point error causes failure
- Confusing power of two with power of four
n elements using bitmask DP with iterative tabulation. Identify the line containing the subtle bug that causes dp[(1 << n) - 1] to remain empty.def generate_permutations_iterative(n):
dp = [[] for _ in range(1 << n)]
# Missing initialization of dp[0]
for mask in range(1 << n):
for i in range(n):
if not (mask & (1 << i)):
for perm in dp[mask]:
dp[mask | (1 << i)].append(perm + [i])
return dp[(1 << n) - 1]Solution
Step 1: Check base case initialization
dp[0] must be initialized to contain an empty permutation to start building others.Step 2: Identify impact of missing dp[0] initialization
Without dp[0] = [[]], dp[mask] lists remain empty, so no permutations are generated.Final Answer:
Option D -> Option DQuick Check:
Adding dp[0] = [[]] fixes the empty result issue [OK]
- Forgetting to initialize dp[0]
- Misunderstanding bitmask iteration order
Solution
Step 1: Compare common_mask calculation with correct formula
The correct mask is the negation of the AND of ones and twos, i.e., ~(ones & twos), not ~(ones | twos).Step 2: Understand impact of wrong mask
Using OR instead of AND causes bits to be cleared incorrectly, failing to reset bits appearing thrice properly.Final Answer:
Option C -> Option CQuick Check:
Correct mask uses AND, not OR, to clear bits appearing three times [OK]
- Using OR instead of AND in mask
- Misordering bit updates
Solution
Step 1: Identify loops in the algorithm
The algorithm traverses the array twice: once to XOR all elements, once to partition and XOR groups.Step 2: Analyze time and space complexity
Each traversal is O(n), no nested loops. Space used is constant (variables only), no extra arrays.Final Answer:
Option B -> Option BQuick Check:
Two linear passes, constant space [OK]
- Confusing with sorting complexity
- Assuming nested loops in partition
- Forgetting constant space usage
Solution
Step 1: Consider input domain
Since n can be zero or negative, these are not powers of four, so must return False immediately.Step 2: Apply logarithm check on absolute value
After filtering invalid inputs, apply logarithm on abs(n) to check power of four.Step 3: Finalize correct approach
Adding a check to return False for zero or negative inputs before log check ensures correctness and avoids math domain errors.Final Answer:
Option B -> Option BQuick Check:
Zero and negatives are filtered out before log check on abs(n) [OK]
- Removing input validation
- Applying log on negative numbers causing errors
