Each child wants a cookie at least as big as their greed. Sort both lists and walk the cookies smallest first, handing each to the least greedy child it can satisfy, so no big cookie is wasted, in O(n log n + m log m).
▼The problem
LeetCode 455 (Easy). Child i has a greed factor g[i], the smallest cookie size that makes them content; cookie j has size s[j]. Each child gets at most one cookie, and child i is content if their cookie has size >= g[i]. Return the most children that can be made content.
Examples (LeetCode's): g = [1, 2, 3], s = [1, 1] → 1; g = [1, 2], s = [1, 2, 3] → 2.
The solution
def findContentChildren(g, s):
g.sort()
s.sort()
i = 0
for size in s:
if i < len(g) and size >= g[i]:
i += 1
return iTranscript
Assign Cookies. A row of children waits by a cookie conveyor. Each child has a greed factor: the smallest cookie that will make them content. Each child gets at most one cookie. How many children can you make content?
Take greeds one, two and three, and two cookies of size one. One cookie feeds the first child. The other is too small for anyone else, so the answer is one. With greeds one and two, and cookies one, two and three, both children are content: two.
The slow way tries every way of handing out the cookies. Three cookies and three children already give six ways to check. Ten cookies have over three million orders.
The key idea is greedy. Sort the children by greed and the cookies by size. Offer the smallest cookie to the least greedy child still waiting. If it's big enough, hand it over. If not, skip it: every child left is at least as greedy. And never spend a big cookie on a small appetite. Swapping in the smaller cookie never makes things worse.
In code, sort both lists and keep a pointer on the next hungry child. Loop over the cookies, smallest first. If a child is still waiting and the cookie is big enough, feed them and move the pointer on. The pointer ends on the answer.
Now a bigger example. Greeds two, three, one, two. Cookies one, four, one, two. Sorted: children one, two, two, three; cookies one, one, two, four. Cookie one feeds greed one. The next one is too small for greed two: skip. Cookie two feeds a two. Cookie four feeds the other two. Greed three still waits, but the cookies are gone. Three content children.
Sorting costs n log n for the children and m log m for the cookies. The walk after that is linear: each cookie is looked at once. Beyond the sort, the extra space is just one pointer.
Sort both, offer the smallest cookie first, feed or skip. That's Assign Cookies.