Greedy Algorithms · Two pointers · Sorting

Assign Cookies Visualizer

What is Assign Cookies

Each child has a greed factor g[i], the minimum cookie size that makes that child content. Each cookie has a size s[j]. A child receives at most one cookie, and a cookie goes to at most one child. Return the maximum number of content children.

Example 1. The cookie of size 1 feeds the child of greed 1. The other cookie is also 1, so the children of greed 2 and 3 stay hungry.

greed   = 1 2 3
cookies = 1 1
Output: 1

Example 2. After sorting, cookie 1 feeds greed 1 and cookie 2 feeds greed 2. Cookie 3 is left over.

greed   = 1 2
cookies = 1 2 3
Output: 2

Approach

Try every assignmentMatching children to cookies is a bipartite assignment. Searching every pairing is exponential in the number of children.
Smallest sufficient cookieSort both rows. Point at the smallest child and the smallest cookie. A cookie smaller than this child is smaller than every later child, so discard it. Otherwise assign it and move both pointers. Saving a larger cookie for a greedier child never helps the current child.

Interactive visualization

Step through the greedy choice

The walk starts on the first pseudocode line. Next and Play move one step at a time, and the highlighted line is the line that just ran.

sort greed and cookies ascending
i = 0, j = 0, content = 0
while i < children and j < cookies:
if cookies[j] < greed[i]: j += 1
else: content += 1; i += 1; j += 1
return content
Step 0 Answer —

Complexity

PieceCostWhy
TimeO(n log n)Sorting dominates. The two pointers then walk each row once.
SpaceO(1)Extra memory is the two pointers, aside from the sort.
Greedy choiceSmallest fitA cookie too small for this child is useless later. A larger cookie should be saved.

Implementation

def find_content_children(greed, cookies): greed = sorted(greed) cookies = sorted(cookies) i = j = content = 0 while i < len(greed) and j < len(cookies): if cookies[j] < greed[i]: j += 1 else: content += 1 i += 1 j += 1 return content