Practice
g = [1, 2, 3] and s = [1, 1]?Solution
Step 1: Trace first iteration
g and s sorted: g=[1,2,3], s=[1,1]. i=0, j=0, count=0. s[0]=1 ≥ g[0]=1 -> count=1, i=1, j=1.Step 2: Trace second iteration
i=1, j=1, count=1. s[1]=1 < g[1]=2 -> j=2. Loop ends as j=2 equals len(s).Final Answer:
Option B -> Option BQuick Check:
Only one cookie satisfies a child's greed [OK]
- Counting cookies not sufficient for greed
- Off-by-one in loop conditions
- Ignoring pointer increments
def twoCitySchedCost(costs):
costs.sort(key=lambda x: x[0] - x[1])
n = len(costs) // 2
total = 0
for i, cost in enumerate(costs):
if i < n:
total += cost[0]
else:
total += cost[1]
return total
costs = [[10,20],[30,200],[400,50],[30,20]]
print(twoCitySchedCost(costs))
Solution
Step 1: Sort costs by difference cost[0] - cost[1]
Differences: [10-20=-10, 30-200=-170, 400-50=350, 30-20=10]. Sorted: [[30,200], [10,20], [30,20], [400,50]]Step 2: Assign first half to city A, rest to city B and sum costs
First two: city A costs = 30 + 10 = 40; last two: city B costs = 20 + 50 = 70; total = 40 + 70 = 110Final Answer:
Option C -> Option CQuick Check:
Sum matches manual calculation [OK]
- Misordering after sorting by difference
- Off-by-one in loop boundary
- Adding wrong city cost for last half
Solution
Step 1: Identify sorting costs
Sorting greed array of size n costs O(n log n), sorting cookies array of size m costs O(m log m).Step 2: Analyze assignment loop
Two pointers scan both arrays once, costing O(n + m).Final Answer:
Option C -> Option CQuick Check:
Sorting dominates complexity, linear scan is minor [OK]
- Assuming nested loops cause O(n*m)
- Ignoring sorting cost
- Confusing linear scan with quadratic
Solution
Step 1: Trace output for input [0,0,0]
After sorting, nums_str is ['0', '0', '0'], concatenation is '000'.Step 2: Identify missing check for all zeros
Without checking if first element is '0', the function returns '000' instead of '0'.Final Answer:
Option A -> Option AQuick Check:
Adding a check to return '0' if nums_str[0] == '0' fixes the bug [OK]
- Forgetting all-zero check
- Incorrect comparator logic
- Sorting without custom comparator
Solution
Step 1: Understand reuse effect
Cookies can be assigned multiple times, so cookie pointer j should not advance on assignment.Step 2: Modify greedy accordingly
Keep sorting both arrays, but only increment child pointer i when a cookie satisfies a child; j stays to reuse the same cookie.Final Answer:
Option D -> Option DQuick Check:
Not incrementing j allows cookie reuse [OK]
- Incrementing both pointers breaks reuse
- Using brute force unnecessarily
- Ignoring sorting leads to suboptimal matches
