AlgoInsight

DSA problem

Assign Cookies

EasyGreedyPattern: Greedytop600AmazonMicrosoftGoogleAdobeBloomberg

Assume you are an awesome parent and want to give cookies to your children. Each child i has a greed factor g[i], the minimum size of a cookie that will content them, and each cookie j has a size s[j]. If s[j] >= g[i], you may assign cookie j to child i and the child becomes content. Each child can receive at most one cookie. Your goal is to maximize the number of content children and return that maximum.

The problem is a classic assignment task that hides a clean greedy structure. Because each child consumes exactly one cookie and each cookie can satisfy at most one child, no clever combinatorial swap can ever beat a strategy that locally picks the best available match. The challenge is choosing what "best" means so the greedy choice does not block future matches.

The trick is to sort both arrays in ascending order and then walk them with two pointers. Always try to satisfy the least greedy remaining child with the smallest cookie that fits. If the current cookie is too small, skip it — no smaller child remains to use it later because we already processed everyone with a smaller greed. If it fits, count a content child and advance both pointers; otherwise advance only the cookie pointer.

This pairing is optimal by an exchange argument: any optimal solution that assigns a larger cookie to an easy child can be re-paired with the smallest sufficient cookie without losing any contentment. Sorting costs O(n log n + m log m) and the two-pointer pass costs O(n + m), giving total O(n log n + m log m) time with O(1) extra space beyond the sort.

Examples

Example 1
Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation: You have 3 children with greed 1, 2, 3 and 2 cookies of size 1. The child with greed 1 can be satisfied by either cookie, but the other two children need larger cookies. So the maximum number of content children is 1.
Example 2
Input: g = [1,2], s = [1,2,3]
Output: 2
Explanation: You have 2 children with greed 1 and 2, and 3 cookies. Give the size-1 cookie to the greed-1 child and the size-2 (or size-3) cookie to the greed-2 child. Both children are content.
Example 3
Input: g = [10,9,8,7], s = [5,6,7,8]
Output: 2
Explanation: After sorting g = [7,8,9,10] and s = [5,6,7,8], the cookie of size 7 satisfies the child with greed 7 and the cookie of size 8 satisfies the child with greed 8. The remaining children need bigger cookies.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

greedytwo-pointerssorting

Browse all DSA problems