LeetCode #455 Easy

Assign Cookies

Assign Cookies is 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]. Give each child at most one cookie and return the largest number of content children.

  • A child is content when s[j] >= g[i]; an equal size is enough.
  • There may be no cookies at all (s can be empty).

Both lists hold up to 3 · 10⁴ values, so trying every pairing is out; sorting plus one pass is the target.

Constraints
  • 1 <= g.length <= 3 * 10⁴
  • 0 <= s.length <= 3 * 10⁴
  • 1 <= g[i], s[j] <= 2³¹ - 1
greedysortingtwo pointers
Open on LeetCode ↗
02

Intuition

To feed the most children, never spend a big cookie on a child a smaller one would satisfy. So serve children from the least greedy up, and hand out cookies from the smallest up.

  • A cookie that fits: give it to the least greedy child still waiting. A larger cookie would also work, but it may be the only one that fits a greedier child later.
  • A cookie that is too small: it is too small for every child still waiting too, because they are all at least as greedy. Throw it away.

Each cookie is looked at once and never comes back, so after sorting the matching is a single pass.

How to spot this pattern

Two lists where one item can "cover" another, each used at most once, and you want the most pairs: sort both and match smallest-to-smallest with two pointers. LeetCode 2410 (Maximum Matching of Players With Trainers) is the same problem, and the pattern returns in Boats to Save People and in interval scheduling.

03

Approach

Try it first

Before reading on: for greed [1, 2, 3] and cookies [1, 1], who should get the cookies? Then try greed [7, 8, 9, 10] and cookies [5, 6, 7, 8]: which cookies can never help anyone, and how can you tell without checking every child?

1

Sort both lists

Sort the greed factors and the cookie sizes in ascending order. Now the next child in line is always the least greedy one still waiting, and the next cookie is always the smallest one left.

2

Offer each cookie to the next child

Walk the cookies from smallest to largest with a pointer child into the greed list. For each cookie:

  • cookie >= g[child]: the child is content; move child forward.
  • otherwise: leave child where it is and go to the next cookie.

A skipped cookie is never needed again: every child after child is at least as greedy.

3

Stop when every child is content

If child reaches len(g), the remaining cookies have nobody to go to, so break out of the loop. Otherwise the loop simply ends when the cookies run out.

4

Return the child pointer

child moved forward once per content child, so it is the answer. No separate counter is needed.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findContentChildren(self, g: List[int], s: List[int]) -> int:
▶3 g.sort()
▶4 s.sort()
▶5 child = 0
▶6 for cookie in s:
▶7 if child == len(g):
▶8 break
▶9 if cookie >= g[child]:
▶10 child += 1
▶11 return child
greedcookies1child2311cookiegreedboth sorted, smallest first
child0children content so far
g[1, 2, 3]sorted
s[1, 1]sorted
Sort both lists. Now child always points at the least greedy child still waiting, and the cookies arrive from smallest to largest.
greedcookies1child231cookie1cookiegreed1≥1cookie 1 ≥ greed 1 → child content
child0children content so far
cookie1
g[child]1
Cookie 1 is at least greed 1, so this child is content. It is the smallest cookie left, so no larger cookie is spent on a child who did not need one. child moves to 1.
greedcookies12child311cookiecookiegreed1<2cookie 1 < greed 2 → skip cookie
child1children content so far
cookie1
g[child]2
Cookie 1 is smaller than greed 2. Every child still waiting is at least that greedy, so this cookie fits nobody: drop it. child stays, a bigger cookie may come next.
greedcookies12311cookiegreedreturn 1
answer1content children
Return 1. 2 children are left without a cookie: the cookies ran out first.
05

Common pitfalls

Sorting only one of the lists

✗ Wrong
s.sort()
# g left in input order
✓ Right
g.sort()
s.sort()

Skipping a cookie is only safe when every child still waiting is at least as greedy as the current one. With greed [3, 1] and cookies [1, 3], the unsorted walk skips cookie 1 for child 3, gives cookie 3 to child 3, and never feeds child 1: the answer comes out 1 instead of 2.

Using > instead of >=

✗ Wrong
if cookie > g[child]:
✓ Right
if cookie >= g[child]:

A cookie exactly the size of the greed factor makes the child content. With g = [1, 2] and s = [1, 2], the strict test feeds nobody and returns 0 instead of 2.

Moving to the next child when the cookie is too small

✗ Wrong
if cookie >= g[child]:
    child += 1
else:
    child += 1
✓ Right
if cookie >= g[child]:
    child += 1

The child who was refused is still the least greedy one waiting, and a bigger cookie may come next. Moving past them counts a child who got nothing: with g = [1, 2, 3] and s = [1, 1] the answer comes out 2 instead of 1.

06

Complexity

Time
O(n log n + m log m)
Space
O(1)
n children and m cookies. The two sorts dominate; the matching pass is O(n + m). Extra space is O(1) beyond whatever the sort itself uses.
07

Assign Cookies FAQ

Why is the greedy choice guaranteed to be optimal?

Take any best assignment. If the least greedy child gets a cookie bigger than the smallest one that fits them, swap the two cookies: the child still fits the smaller one, and whoever held the smaller one now holds a bigger one, so nobody loses. Repeating the swap turns any best assignment into the greedy one without losing a child, so greedy reaches the maximum too.

Is there a brute-force solution?

For each child, scan all unused cookies for the smallest one that fits, and mark it used. That is O(n · m) and passes small inputs, but the sorted two-pointer walk does the same matching in one pass after sorting.

Does sorting in descending order work?

Yes, if you flip the roles: walk children from the greediest down, and give the largest remaining cookie to a child only if it fits; a child it does not fit is skipped, since no smaller cookie will fit them either. It returns the same count.