Practice
Solution
Step 1: Understand the problem constraints
The array is sorted, and duplicates are allowed at most twice, so we can leverage order.Step 2: Identify the approach that uses two pointers and index offset check
This approach compares the current element with the element two positions before the write pointer to decide if it should be written, ensuring O(n) time and O(1) space.Final Answer:
Option B -> Option BQuick Check:
Two pointers with index offset check is the known optimal approach [OK]
- Using nested loops causes O(n²) time
- Hash maps use extra space
- DP is unnecessary here
Solution
Step 1: Identify loops and sorting cost
Sorting takes O(n log n). The main loop runs O(n) times.Step 2: Analyze inner two-pointer loop
For each i, two pointers scan the remaining array once, total O(n) per i.Final Answer:
Option A -> Option AQuick Check:
Overall time is O(n log n + n^2) -> O(n^2) dominates [OK]
- Confusing two-pointer scan as O(n^2) per iteration
- Ignoring sorting cost or assuming it dominates
- Assuming binary search is used inside two-pointer
Solution
Step 1: Analyze the condition for backspace handling
The condition 'elif write >= 0' allows write to decrement even when write is 0, causing write to become -1, which is invalid and leads to incorrect string reconstruction.Step 2: Correct condition
The condition should be 'elif write > 0' to prevent write from going negative and ensure backspaces at the start are handled safely.Final Answer:
Option B -> Option BQuick Check:
write pointer must not go below zero [OK]
- Allowing write to become negative on backspace
- Returning arr[:write] without checking write validity
- Misplacing the backspace condition
Solution
Step 1: Identify loops and operations
The algorithm scans the array twice sequentially: once to overwrite non-zero elements, once to fill zeroes.Step 2: Analyze time and space
Each loop is O(n), total O(n). No extra arrays or recursion used, so space is O(1).Final Answer:
Option A -> Option AQuick Check:
Two linear passes, constant extra space [OK]
- Mistaking two loops as nested (O(n^2))
- Assuming extra space due to overwriting
- Confusing with sorting complexity
def moveZeroes(nums):
lastNonZeroFoundAt = 0
for num in nums:
if num != 0:
nums[lastNonZeroFoundAt] = num
lastNonZeroFoundAt += 1
# Bug introduced here
for i in range(lastNonZeroFoundAt, len(nums)):
nums[i] = nums[i]
What is the bug in this code?Solution
Step 1: Analyze second loop behavior
The second loop assigns nums[i] = nums[i], which does nothing and fails to fill zeroes.Step 2: Identify correct fix
It should assign nums[i] = 0 to move zeroes to the end properly.Final Answer:
Option C -> Option CQuick Check:
Zeroes remain unfilled, causing incorrect output [OK]
- Forgetting to fill zeroes after moving non-zero elements
- Misunderstanding loop purpose
