Assign Cookies (LeetCode 455): Solution and Explanation

Easy
Array
Two Pointers
Greedy
Sorting

Each child has a greed factor, the smallest cookie size that makes them content, and each cookie has a size. Every child can get at most one cookie. Return the largest number of children that can be made content.

Intuition

Think about the least greedy child. Anything that satisfies a greedier child also satisfies them, so they are the easiest to serve and should be served first.

Which cookie should they get? The smallest one that is big enough. Handing them a large cookie would waste size that a greedier child might need later, while the smallest sufficient cookie is useless to nobody else in a way that matters.

That suggests sorting both lists and walking the cookies from small to large. A cookie smaller than the least greedy hungry child is smaller than every hungry child, so it can be thrown away. A cookie that fits goes to that child, and the next child becomes the target.

This is a classic exchange argument: any optimal assignment can be rearranged, without losing a content child, into the one the greedy builds.

Approach: Sort and match with two pointers

  1. Sort g (greed factors) and s (cookie sizes) in ascending order.
  2. Set child = 0, the least greedy child not yet content.
  3. For each cookie size from smallest to largest, if child < len(g) and size >= g[child], give it to that child and increase child.
  4. Otherwise the cookie is too small for every remaining child; move on to the next cookie.
  5. Return child, which counts the content children.

Step-by-step example

g = [1,2,3], s = [1,1]
  1. Both arrays are already sorted: greed 1, 2, 3 and cookies 1, 1.
  2. child = 0 points at the child with greed 1.
  3. The first cookie has size 1, which is at least 1, so that child is content. child = 1.
  4. The second cookie has size 1, but the next child needs 2. It is too small for them and for the child needing 3, so it is skipped.
  5. No cookies remain. Return 1.

Code: Python, Java, C++

1class Solution:
2    def findContentChildren(self, g: List[int], s: List[int]) -> int:
3        g.sort()
4        s.sort()
5        child = 0
6        for size in s:
7            if child < len(g) and size >= g[child]:
8                child += 1
9        return child
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n + m log m)

Sorting the n greed factors and m cookie sizes dominates. The matching pass is a single O(m) loop.

Space

O(1)

The arrays are sorted in place and only one pointer is kept, aside from whatever the sort itself uses.

Other approaches

Greediest child first (time O(n log n + m log m), space O(1))

Walk children from most to least greedy with a pointer on the largest cookie. If the largest cookie satisfies the child, give it; otherwise skip the child. Equally optimal and equally fast.

Best fit with a sorted multiset (time O((n + m) log m), space O(m))

For each child in any order, find and remove the smallest cookie at least as big as their greed using a balanced tree. Works, but only after sorting children, and it needs extra structure for no gain.

Common mistakes

  • Forgetting the child < len(g) check. Once every child is content, reading g[child] would go out of bounds.
  • Sorting only one array. The skip rule depends on both being in ascending order.
  • Moving the child pointer when a cookie is too small. The child is still hungry; only the cookie should be skipped.
  • Missing the empty cookie list. With no cookies the answer is 0 and the loop never runs.

Frequently asked questions

Why is it safe to discard a cookie that is too small?

It is smaller than the greed of the least greedy hungry child, and every other hungry child is at least as greedy. No remaining child can use it.

Why give the smallest sufficient cookie instead of any cookie that fits?

A larger cookie could satisfy a greedier child later, while the smaller one might not. Using the smallest one that works keeps every option open, which is why the greedy count is never beaten.

Does the order I loop over matter, cookies or children?

Either works if both arrays are sorted. Looping over cookies and advancing a child pointer is the shortest form; looping over children and advancing a cookie pointer gives the same count.