You have some children and some cookies. Child i is happy only with a cookie of size at least g[i], its greed. Cookie j has size s[j].
Each child can get at most one cookie, and each cookie goes to at most one child. Return the largest number of children you can make happy.
Example 1
Input: g = [2, 4, 1], s = [3, 1, 2] Output: 2 Why: greeds 1 and 2 get sizes 1 and 2; nothing left is 4 or more
2 more examples and the constraints
Example 2
Input: g = [1, 3], s = [4, 2, 1] Output: 2 Why: size 1 for greed 1, size 4 for greed 3
Example 3
Input: g = [5], s = [] Output: 0 Why: there are no cookies to hand out
Constraints
- 1 ≤ length of g ≤ 30,000
- 0 ≤ length of s ≤ 30,000 (there may be no cookies)
- 1 ≤ g[i], s[j] ≤ 2,147,483,647
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan for each childO(n·m)
- Two pointers after sortingO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30,000 children and cookies | Verdict |
|---|---|---|---|
| Scan for each child | O(n·m) | Right idea, slow search | |
| Two pointers after sorting | O(n log n + m log m) | Best; sort, then one pass |
n = number of children, m = number of cookies.
Edge cases to test
- No cookies. s = [] gives 0 right away.
- Every cookie too small. g = [5, 6], s = [1, 2, 3] gives 0.
- More cookies than children. g = [1], s = [1, 1, 1] gives 1: stop counting once every child is fed.
- Huge values. Greed and size can be 2,147,483,647; compare them directly, never by subtracting.
- Unsorted input. g = [10, 9, 8, 7], s = [5, 6, 7, 8] gives 2 only after sorting both lists.
Common mistakes
- Forgetting the
child < len(g)check, so extra cookies read past the last child. - Giving each child the biggest cookie, which wastes cookies a greedier child needed.
- Sorting only one of the two lists.
How to talk through it
- 1Clarify. Can a child get two cookies? Can there be no cookies? Are the lists sorted?
- 2Give the brute force. Sort, then for each child scan for the smallest free cookie that fits: O(n·m).
- 3State the greedy rule. Least greedy child first, smallest cookie that fits. Swapping shows it never loses.
- 4Code the two pointers. One loop over the sorted cookies; move the child pointer when a cookie fits.
- 5Test out loud. Run the no-cookie and all-too-small cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?