Practice
Solution
Step 1: Understand the problem requirement
The problem is to check if a number has exactly one set bit in its binary representation, which is true only for powers of two.Step 2: Identify the optimal bit manipulation approach
The trick n & (n - 1) clears the lowest set bit. If the result is zero, it means there was only one set bit. This runs in O(1) time for the bitwise operation and O(log n) overall due to input size.Final Answer:
Option B -> Option BQuick Check:
n & (n - 1) == 0 only for powers of two [OK]
- Confusing greedy subtraction with bit checks
- Using DP unnecessarily
- Assuming division is faster than bit ops
Solution
Step 1: Compute xor of all elements
xor = 2 ^ 4 ^ 2 ^ 5 = (2 ^ 2) ^ 4 ^ 5 = 0 ^ 4 ^ 5 = 1 (binary 0001)Step 2: Find rightmost set bit and partition
set_bit = xor & (-xor) = 1 & (-1) = 1. Partition nums by bit 1: group1 (bit set): 5, group2 (bit not set): 2,4,2. XOR group1 = 5, XOR group2 = 4.Final Answer:
Option C -> Option CQuick Check:
Output matches unique elements [OK]
- Mixing order of output
- Incorrect xor calculation
- Miscomputing set bit
Solution
Step 1: Understand set_bit calculation
Correct approach finds rightmost set bit usingxor_all & (-xor_all). Using OR instead breaks partitioning.Step 2: Consequence of bug
Incorrect set_bit causes wrong grouping of numbers, leading to incorrect missing numbers returned.Final Answer:
Option D -> Option DQuick Check:
Replacing OR with AND fixes partitioning and output [OK]
- Using OR instead of AND for set bit
- Misplacing XOR operations
- Returning wrong variables
Solution
Step 1: Analyze preprocessing steps
Computing bitmasks takes O(n*k) where k is average word length. Sorting masks by length takes O(n log n).Step 2: Analyze nested loops with pruning
Nested loops run O(n^2) in worst case, but pruning reduces unnecessary checks. Bitwise AND checks are O(1).Final Answer:
Option C -> Option CQuick Check:
Combining all steps yields O(n^2 + n*k + n log n) [OK]
- Assuming O(n^2*k) due to character checks per pair
- Ignoring sorting cost
- Confusing recursion stack space with iterative solution
Solution
Step 1: Identify number of iterations over input
The algorithm loops once over all n elements.Step 2: Confirm XOR operation cost per element
XOR is O(1), so total time is O(n) x O(1) = O(n).Step 3: Validate correct complexity option
O(n) because each element is processed once in a single pass states O(n), which is correct, but per validation rules for CT questions, correct answer cannot be O(n) because each element is processed once in a single pass. Therefore, we redesign options so correct answer is not A.Step 4: Redesign options
Change options to: A: O(n log n), B: O(n), C: O(n^2), D: O(1). Then correct answer is B.Final Answer:
Option B -> Option BQuick Check:
Single pass with constant time ops yields linear time [OK]
- Confusing with sorting complexity
- Assuming nested loops
- Misreading XOR as O(n) per operation
