Practice
grayCode(2)?Solution
Step 1: Compute values for i in range(4)
For i=0: 0 ^ (0>>1)=0; i=1: 1 ^ (0)=1; i=2: 2 ^ (1)=2^1=3; i=3: 3 ^ (1)=3^1=2Step 2: Collect results in list
The sequence is [0, 1, 3, 2], which matches the Gray code property.Final Answer:
Option C -> Option CQuick Check:
Manual XOR calculation confirms the sequence [0,1,3,2] [OK]
- Confusing the order of XOR and shift
- Off-by-one errors in range leading to missing or extra elements
- Misinterpreting the output as binary numbers instead of integers
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
n & (n - 1) to check if a number is a power of two, assuming n is a 32-bit integer?Solution
Step 1: Identify the operation cost
The operation n & (n - 1) runs in constant time on fixed-width integers, such as 32-bit integers.Step 2: Consider input size in bits
Since the integer size is fixed (32 bits), the operation is O(1) constant time.Final Answer:
Option C -> Option CQuick Check:
Bitwise operations on fixed-width integers are constant time [OK]
- Assuming O(log n) for fixed-width integers
- Confusing numeric value with bit length
def reverseBits(n: int) -> int:
n = ((n >> 1) & 0x55555555) | ((n & 0x55555555) << 1)
n = ((n >> 2) & 0x33333333) | ((n & 0x33333333) << 2)
n = ((n >> 4) & 0x0f0f0f0f) | ((n & 0x0f0f0f0f) << 4)
n = ((n >> 8) & 0x00ff00ff) | ((n & 0x00ff00ff) << 8)
n = (n >> 16) | (n << 16) # Bug here: missing mask
return n
What is the bug in this code?Solution
Step 1: Identify the last step
The last line shifts bits by 16 left and right but does not mask the result to 32 bits.Step 2: Understand impact
Without masking, bits can overflow beyond 32 bits, causing incorrect reversal results.Final Answer:
Option D -> Option DQuick Check:
Masking with 0xffffffff fixes overflow [OK]
- Forgetting to mask after left shifts
- Misusing masks in earlier steps
- Confusing left and right shifts
Solution
Step 1: Identify the number of iterations
The algorithm iterates over each byte exactly once, so the outer loop runs n times.Step 2: Analyze operations per iteration
Each iteration performs a fixed number of bitwise operations and conditional checks, all O(1).Final Answer:
Option A -> Option AQuick Check:
Single pass with constant work per byte -> O(n) time [OK]
- Confusing bitwise ops as log n
- Assuming nested loops cause O(n^2)
