15% off all plans & roadmaps Use code
See plansAssign Cookies
- LeetCode 455
- Easy
- Greedy Patterns
- Sorting Based
Updated
TL;DR: Each child needs a cookie at least as big as their greed factor, and each cookie can feed only one child. Sort both lists, then walk them together and feed the least greedy child with the smallest cookie that works.
Problem
You are a parent who wants to give cookies to your children. Give each child at most one cookie.
Child i has a greed factor g[i]. That is the minimum cookie size the child needs to be content. Cookie j has size s[j]. If s[j] >= g[i], you can give cookie j to child i, and that child will be content.
Your goal is to maximize the number of content children. Return that maximum number.
Example 1
Input: g = [1,2,3], s = [1,1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of the children are 1, 2, 3. Both cookies have size 1, so only the child with greed factor 1 can be content. The answer is 1.
Example 2
Input: g = [1,2], s = [1,2,3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors are 1 and 2. The cookie sizes 1, 2, and 3 satisfy both children. The answer is 2.
Constraints
1 <= g.length <= 3 * 10^40 <= s.length <= 3 * 10^41 <= g[i], s[j] <= 2^31 - 1
Constraints that matter
- Up to 3 * 10^4 children and cookies rules out trying every assignment. You need a sort-based method that runs in about n log n time.
- Each cookie serves at most one child. Once a cookie is given away, it is gone for everyone else, so you must track which cookies are used.
- Sizes go up to 2^31 - 1, but the problem only compares values. No arithmetic happens, so overflow cannot change the answer in any language.
- s.length can be 0. The answer must be 0 in that case, and your loops must not read
s[0].
Hints
Hint 1
This is a matching problem with a threshold rule.
Hint 2
Each child either goes without a cookie, or takes any unused cookie that fits.
Solution
Intuition
This is a matching problem with a threshold rule. A cookie fits a child when its size is at least the greed factor, so each child has a set of acceptable cookies. The sorting-based greedy pattern fits because only the order of values matters, not their exact sizes.
Picture two sorted lines, one of people and one of boxes, both ordered by size. The cookie pointer is the box you hold, and the child pointer is the person at the front of the line.
Sorting both lists turns the matching into a walk along two lines. Start with the least greedy child. Any cookie that fits this child also fits every greedier child. Giving the smallest fitting cookie keeps the bigger cookies for the children who need them.
If the smallest cookie is too small for the least greedy unfed child, it is too small for everyone. Every other unfed child needs at least as much. That cookie can be discarded, and you move to the next one.
An exchange argument confirms the choice. If an optimal plan skips a match here, swap in the smallest fitting cookie for this child. The plan stays valid and feeds the same number of children.
Worked example
Input: g = [10, 9, 8, 7], s = [5, 6, 7, 8] Output: 2 Explanation: Sorted, the greed factors are 7, 8, 9, 10 and the cookie sizes are 5, 6, 7, 8. Cookie 7 feeds the child with greed 7, and cookie 8 feeds the child with greed 8. Greed 9 and greed 10 have no cookie left, so the answer is 2.
Approach 1: Brute force search
Each child either goes without a cookie, or takes any unused cookie that fits. Try both options for every child and keep the larger count. This covers every valid assignment, so the answer is correct. The search grows exponentially, so treat it as a baseline that shows the full space of choices.
Steps
- Keep a
usedflag for each cookie, all set to false at the start. - Define best(i) as the most children you can feed from child i to the end.
- Option one: skip child i and take best(i + 1).
- Option two: for each unused cookie j with s[j] >= g[i], mark it used, take 1 plus best(i + 1), then unmark it.
- Return the larger value from the two options. When i equals the number of children, return 0.
- Call best(0) and return that value.
Dry run
Start with best(0) on the given order g = [10, 9, 8, 7] and s = [5, 6, 7, 8], with no cookie used.
- best(0), child 10: no cookie reaches 10, so only the skip branch runs. best(0) = best(1).
- best(1), child 9: no cookie reaches 9. best(1) = best(2).
- best(2), child 8: skip gives best(3). Cookie 8 fits, so mark it used and take 1 + best(3).
- best(3), child 7, with cookies 5, 6, 7 free: skip gives 0. Cookie 7 fits, so take 1 + best(4) = 1. best(3) = 1.
- Back in best(2): skip gives 1 and the cookie 8 branch gives 1 + 1 = 2. best(2) = 2.
- best(1) = 2 and best(0) = 2. The output is 2.
Complexity
| Time | O((m + 1)^n) |
|---|---|
| Space | O(n + m) |
Let n be the number of children and m the number of cookies. Each call to best(i) either skips child i or picks one of at most m cookies, so it makes at most m + 1 recursive calls. The recursion is n levels deep, so the call tree has at most (m + 1)^n paths, which bounds the work. The call stack holds n frames and the used array holds m flags, so space is O(n + m).
PythonTested in our runner
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
used = [False] * len(s)
def best(i: int) -> int:
# Most children that can be content from child i onward
if i == len(g):
return 0
result = best(i + 1) # child i gets no cookie
for j in range(len(s)):
if not used[j] and s[j] >= g[i]:
used[j] = True
result = max(result, 1 + best(i + 1))
used[j] = False # undo, then try the next cookie
return result
return best(0)The Sorting Based infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Sorting Based
Part of Greedy Patterns
Approach 2: Sort both, then two pointersOptimalSorting Based
The brute force tests every cookie for every child, and it repeats that work in every branch of the search. Sorting removes the search. Once both lists are sorted, the least greedy child meets the smallest cookie. A cookie that fails the current child also fails every later child, so each cookie is discarded at most once and each child is checked once.
Steps
- Sort g in ascending order, so the least greedy child comes first.
- Sort s in ascending order, so the smallest cookie comes first.
- Set child = 0 and cookie = 0. The child index also counts content children.
- While both indexes are inside their arrays, compare s[cookie] with g[child].
- If s[cookie] >= g[child], increment child. That child is fed.
- Increment cookie on every iteration, whether the cookie was used or discarded.
- Return child.
Dry run
Sorted, g = [7, 8, 9, 10] and s = [5, 6, 7, 8]. Each row is one loop iteration.
| Step | child | cookie | Compare s[cookie] with g[child] | Action | count after step |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 5 vs 7 | too small, discard cookie | 0 |
| 2 | 0 | 1 | 6 vs 7 | too small, discard cookie | 0 |
| 3 | 0 | 2 | 7 vs 7 | fed, child moves to 1 | 1 |
| 4 | 1 | 3 | 8 vs 8 | fed, child moves to 2 | 2 |
| 5 | 2 | 4 | cookie index 4 is past the end | loop stops | 2 |
The loop ends with cookie = 4, which equals s.length. The output is child = 2.
Complexity
| Time | O(n log n + m log m) |
|---|---|
| Space | O(1) extra for the pointers, plus the sort's own stack |
Let n be the number of children and m the number of cookies. Sorting g takes O(n log n) and sorting s takes O(m log m). The scan moves child at most n times and cookie at most m times, so it does O(n + m) work. The total is O(n log n + m log m), and the two sorts dominate.
PythonTested in our runner
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort() # least greedy child first
s.sort() # smallest cookie first
child = 0
cookie = 0
while child < len(g) and cookie < len(s):
# The cookie is big enough, so feed this child
if s[cookie] >= g[child]:
child += 1
# The cookie was used or was too small, so move on either way
cookie += 1
return childCommon mistakes
child++placed outside theif, so discarded cookies still count as fed children. Incrementchildonly inside the match branch.- Comparing the wrong way round, as in
g[child] >= s[cookie]. The cookie must meet the greed, so checks[cookie] >= g[child]. - Sorting only one array. A sorted
gagainst an unsortedsmakes the pointer walk meaningless. Sort both. - Calling JavaScript
g.sort()with no comparator. The default sort compares strings, so 10 comes before 9. Pass(a, b) => a - b. - A first-fit brute force that takes the first cookie that fits and never reconsiders. With g = [1, 2] and s = [2, 1], child 1 takes the cookie of size 2 and child 2 is left with size 1, giving 1 instead of 2. Sorting or full search fixes this.
- Looping while only
child < len(g), then readings[cookie]after the cookies run out. Check both bounds in the loop condition.
Edge cases
- Empty cookie list, g = [1, 2] and s = []. Expected output 0. The loop never runs, so the count stays 0.
- No cookie is big enough, g = [5, 6] and s = [1, 2]. Expected output 0. Every cookie is discarded.
- Equal sizes, g = [3] and s = [3]. Expected output 1, because the rule is greater than or equal to.
- Duplicates, g = [1, 1, 1] and s = [1, 1]. Expected output 2. Two cookies feed two children, and the third child stays unfed.
- More cookies than children, g = [2] and s = [9, 9, 9]. Expected output 1. The extra cookies do nothing.
- Maximum values, g = [2147483647] and s = [2147483647]. Expected output 1. The code only compares values, so nothing overflows.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Assign Cookies, with how to answer them.
Unlock the follow-upsAssign Cookies FAQ
What is the time complexity of Assign Cookies?
The optimal solution runs in O(n log n + m log m) time, where n is the number of children and m is the number of cookies. The two sorts dominate that cost. The final scan adds only O(n + m).
Why use sorting for Assign Cookies?
Sorting lets you match the least greedy child with the smallest cookie that fits. Once both lists are in order, one pointer walk finds every valid match. Without sorting, a first-fit choice can waste a large cookie.
Can Assign Cookies be solved in O(1) extra space?
Yes, if you count only your own variables, since the two pointers use O(1) space. Strictly, the sort also needs working space. Heapsort sorts in place with O(1) extra space, while quicksort-style sorts use O(log n) stack space.
Why does a first-fit greedy fail on Assign Cookies?
First-fit gives each child the first cookie that works, without checking later children. With g = [1, 2] and s = [2, 1], the first child takes the cookie of size 2, and the second child has no cookie left. Sorting both lists first avoids this.
Does the Python solution change the input lists?
Yes. The list.sort() method sorts g and s in place, so the caller sees the sorted lists afterward. If you must keep the original order, copy the lists first with sorted(g) and sorted(s).
Asked at
See which companies ask this — Pro
Related problems
- Lemonade Change · same technique: Sorting Based
- Hand of Straights · same technique: Sorting Based
- Merge Triplets to Form Target Triplet · same technique: Sorting Based
- Sort an Array · same technique: Sorting Based
- Two City Scheduling · same technique: Sorting Based
- Meeting Rooms · same pattern: Greedy Patterns
- Best Time to Buy and Sell Stock · same pattern: Greedy Patterns
- Merge Intervals · same pattern: Greedy Patterns
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns