Practice
Solution
Step 1: Understand problem constraints
The problem requires finding three numbers whose sum is closest to a target, which suggests checking combinations efficiently.Step 2: Identify approach with O(n²) complexity
Sorting the array allows fixing one element and using two pointers to find pairs that sum closest to the remaining target, achieving O(n²) time.Final Answer:
Option A -> Option AQuick Check:
Sorting + two pointers is classic for 3Sum Closest [OK]
- Thinking brute force is optimal
- Confusing DP with this problem
- Assuming greedy works for closest sum
[3, 2, 2, 3] with val = 3, what is the returned new length and the array slice arr[:new_len] after execution?Solution
Step 1: Trace first iteration
start=0, end=3; nums[0]=3 equals val, swap nums[0] and nums[3], array becomes [3,2,2,3], end=2Step 2: Trace subsequent iterations
start=0, nums[0]=3 equals val, swap nums[0] and nums[2], array becomes [2,2,3,3], end=1; start=0, nums[0]=2 not val, start=1, nums[1]=2 not val, start=2 > end=1 loop ends; return start=2Final Answer:
Option A -> Option AQuick Check:
Final length 2 with first two elements [2, 2] [OK]
- Off-by-one errors in loop condition
- Not decrementing end after swap
import bisect
def count_pairs_buggy(nums, K):
count = 0
n = len(nums)
for i in range(n - 1):
target = nums[i] + K
j = bisect.bisect_right(nums, target, i) - 1
if j > i:
count += j - i
return count
Solution
Step 1: Understand bisect_right usage
bisect_right should start searching from i + 1 to avoid counting pairs where j ≤ i.Step 2: Identify bug in line 8
Using i as the start index includes nums[i] itself, causing pairs with i == j or double counting.Final Answer:
Option C -> Option CQuick Check:
Changing i to i + 1 fixes the bug [OK]
- Starting binary search at i instead of i+1
- Off-by-one errors in bisect indices
- Counting pairs where i >= j
Solution
Step 1: Analyze pointer updates after swap
After swapping nums[start] and nums[end], end must be decremented to exclude the swapped val at the end.Step 2: Consequence of missing end decrement
Without end--, the loop may repeatedly swap the same elements, causing infinite loop or incorrect results.Final Answer:
Option A -> Option AQuick Check:
Missing end decrement after swap breaks loop progress [OK]
- Forgetting to decrement end after swap
- Incrementing start incorrectly after swap
Solution
Step 1: Understand immutability constraint
Strings are immutable in Python, so in-place swaps are impossible directly on the string.Step 2: Choose efficient workaround
Converting to a list allows in-place two-pointer swaps, then joining back creates the reversed string efficiently in O(n) time.Final Answer:
Option A -> Option AQuick Check:
Only Convert the string to a list, reverse it using two pointers, then join back to a string. respects immutability and is efficient [OK]
- Trying to swap characters in immutable string
- Using inefficient string concatenation in loop
- Misapplying DP to string reversal
