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
Solution
Step 1: Understand the problem constraints
Two unique elements appear once, others appear twice. We want O(n) time and O(1) space.Step 2: Identify the approach that uses XOR partitioning
XOR all elements to get xor = num1 ^ num2. Find a set bit in xor to partition elements into two groups, each containing one unique number. XOR each group separately to find the unique numbers.Final Answer:
Option A -> Option AQuick Check:
Sorting is O(n log n), hash map uses extra space, greedy fails on duplicates [OK]
- Assuming sorting is linear time
- Using hash map violates O(1) space
- Greedy fails on duplicates
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: Identify input size
The input is an integer n, and the brute force method checks each bit by shifting until n becomes zero.Step 2: Analyze loop iterations
The number of iterations depends on the number of bits in n, which is proportional to log n.Final Answer:
Option A -> Option AQuick Check:
Loop runs approximately log n times, so complexity is O(log n) [OK]
- Assuming fixed bit width means O(1)
- Confusing value magnitude with fixed bit size
Solution
Step 1: Analyze the loop iterations
Each iteration divides n by 4, so the number of iterations is proportional to log base 4 of n.Step 2: Express complexity in Big-O notation
Since log base 4 of n is O(log n), the time complexity is O(log n).Final Answer:
Option D -> Option DQuick Check:
Loop runs ~log4(n) times, which is O(log n) [OK]
- Confusing division steps as O(1)
- Mistaking log log n complexity
