The problem, in one line. Each child will only be happy with a cookie at least as big as their appetite, and each cookie goes to one child at most. Return how many children you can make happy. LeetCode 455.
The tell. Two lists matched one to one, a plain size threshold on each side, and the answer is a count. When nothing links the items except “big enough”, sort both lists and walk them together.
The wrong first idea
Go down the line of children and give each one the first cookie in the box that fits.
for need in g:
for k, c in enumerate(s):
if c >= need:
s.pop(k)
fed += 1
break
It looks fair and it is wrong. With appetites [1, 3] and cookies [3, 1] the child who wants 1 grabs the big cookie, the child who wants 3 gets nothing, and you report 1. Feeding both was possible. It is also a nested loop, so it does n times m work on top of being wrong.
The invariant
Sort both lists. Keep a pointer at the least greedy child who is still hungry, and offer cookies from smallest to largest.
appetites [1, 2] cookies [1, 2, 3]
cookie 1 -> child wants 1 fed
cookie 2 -> child wants 2 fed
cookie 3 -> nobody left
The sentence that stays true every step: the next cookie either feeds the least greedy hungry child or is too small for every hungry child. So a cookie is never wasted on someone who would have been happy with a smaller one, and a too-small cookie can safely be thrown away.
The solution
def find_content_children(g, s):
g.sort()
s.sort()
child = 0
for cookie in s:
if child < len(g) and cookie >= g[child]: # smallest cookie that feeds the least greedy child
child += 1
return child
print(find_content_children([1, 2, 3], [1, 1]))
print(find_content_children([1, 2], [1, 2, 3]))
print(find_content_children([5], [1, 2]))
1
2
0
func findContentChildren(g []int, s []int) int {
sort.Ints(g)
sort.Ints(s)
child := 0
for _, cookie := range s {
if child < len(g) && cookie >= g[child] { // smallest cookie that feeds the least greedy child
child++
}
}
return child
}
Same three calls print 1, 2, 0.
Complexity
- Time O(n log n + m log m): two sorts, then one pass over the cookies.
- Space O(1) extra: both lists are sorted in place and one counter moves.
Traps
- Sorting only the cookies. Appetites
[3, 1]with cookies[1, 3]returns 1 instead of 2, because the pointer sits on the greedy child first. - Using
>instead of>=. One child wanting 2 and one cookie of size 2 returns 0, but that cookie fits exactly. - Feeding the biggest cookie to the first child you meet. Small appetites eat the large cookies and the large appetites go hungry.
Next in the ladder
Maximum Subarray drops the two sorted lists for one running number, and the greedy choice becomes “keep going or start over here”.