Practice
ones after processing the input [2, 2, 3, 2]?Solution
Step 1: Trace variable updates for each num
After processing 2,2,3,2, the variable 'ones' ends up holding the unique number 3.Step 2: Confirm final return value
The function returns 'ones' which is 3, the single number appearing once.Final Answer:
Option A -> Option AQuick Check:
Output matches expected unique element 3 [OK]
- Confusing 'ones' and 'twos' variables
- Off-by-one iteration errors
Solution
Step 1: Understand bitwise sum without +
Bitwise XOR adds bits without carry, while bitwise AND identifies carry bits.Step 2: Repeat until no carry remains
Carry bits are shifted left and added recursively or iteratively until carry is zero, ensuring all bits are summed correctly.Final Answer:
Option A -> Option AQuick Check:
Bitwise XOR and AND with carry loop is the classic sum without + [OK]
- Thinking greedy bit-by-bit addition works without carry handling
- Using DP unnecessarily
- Brute force increment is inefficient
Solution
Step 1: Identify loops in the algorithm
The algorithm iterates over the range 1 to n once and over the input array once, each in separate loops.Step 2: Analyze operations inside loops
Each iteration performs constant time XOR and bitwise operations, so total time is proportional to n.Final Answer:
Option B -> Option BQuick Check:
Two linear passes -> O(n) time [OK]
- Assuming nested loops cause O(n²)
- Thinking bitwise ops add log n factor
- Confusing constant time with O(1) overall
Solution
Step 1: Identify how set_bit is computed
Correct approach uses set_bit = xor & (-xor) to isolate rightmost set bit. Here, set_bit = xor misses this step.Step 2: Understand impact of bug
Without isolating rightmost set bit, partitioning fails, XOR groups won't separate unique numbers correctly.Final Answer:
Option A -> Option AQuick Check:
Bug in set_bit calculation breaks partitioning [OK]
- Using xor directly as set_bit
- Breaking early before full XOR
- Misusing partition condition
Solution
Step 1: Identify number of subsets generated
There are 2^n subsets in total.Step 2: Calculate work done per subset
Each subset can take up to O(n) time to copy or build, so total time is O(n * 2^n).Final Answer:
Option A -> Option AQuick Check:
Exponential subsets times linear work per subset [OK]
- Confusing O(2^n) as total time ignoring subset size
- Mistaking factorial or polynomial complexities
