Assign Cookies

easy

You are handing out cookies to children. Child i will only be content with a cookie whose size is at least their greed factor g[i], and each cookie s[j] can go to at most one child.

Given the greed factors g and the cookie sizes s, return the maximum number of children you can content.

Hints

If you sort both children and cookies, which child should you try to satisfy first?
The least greedy child is easiest to please — match them with the smallest cookie that works.
Sort both ascending and sweep with two pointers, advancing the cookie every step.

Common doubts

Larger cookies can satisfy strictly more children, so spending a bigger cookie than necessary can cost you a match later. The smallest one that works is never worse.
Any cookie that contents a greedy child also contents a less greedy one. Matching the easy child first keeps your options open for the hard ones.
No. The sweep simply stops when either list runs out; leftover cookies or unmatched greedy children don't affect the count.

Interview follow-ups

An exchange argument: take any optimal matching and repeatedly swap so the least greedy child gets the smallest sufficient cookie; each swap keeps the count, converging to the greedy solution.
That changes the problem to a packing/subset-sum flavor and greedy no longer suffices — you'd typically need a different technique.

Fun facts

  • This is a textbook bipartite matching, but the threshold structure (a cookie fits a child iff it's big enough) is exactly what makes the simple greedy optimal.
  • The same 'smallest thing that clears the bar' idea reappears in scheduling and in fitting items to bins.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: g = [1,2,3], s = [1,1]
Output: 1
Three children with greed 1,2,3 and two cookies of size 1. Only the child with greed 1 can be content.
Example 2
Input: g = [1,2], s = [1,2,3]
Output: 2
Both children can be satisfied — greed 1 with a size-1 cookie and greed 2 with a size-2 cookie.
Constraints

- 1 <= g.length <= 3 * 10^4 - 0 <= s.length <= 3 * 10^4 - 1 <= g[i], s[j] <= 2^31 - 1

Solve this problem →