Code Logo

Assign Cookies

Published at24 Jul 2026
Easy 0 views
Like0

Assume you are an awesome parent wanting to give cookies to your children. Each child has a greed factor g[i] (minimum cookie size they will be content with). Each cookie has a size s[j]. Each child can get at most one cookie. Return the maximum number of content children.

Sort both arrays. Use a greedy approach: iterate through children and cookies together. For each child, find the smallest cookie that satisfies their greed. If the current cookie is too small, move to a larger cookie. This ensures larger cookies are saved for greedier children.

Time is O(n log n) for sorting plus O(n) for the greedy pass. Space is O(1).

Edge cases include no cookies (return 0), all children satisfied (return min(len(g), len(s))), and cookies too small for any child.

The greedy approach of matching the smallest sufficient cookie to each child is optimal because any cookie that satisfies a child could also satisfy a less greedy child. By sorting both arrays and using a two-pointer approach, we maximize matches without wasting large cookies on less greedy children.

The two-pointer greedy approach runs in O(max(n,m)) after sorting, making it efficient for large inputs. Sorting both arrays ensures we never skip a child that could have been satisfied by a smaller cookie, maximizing the total number of content children.

Example Input & Output

Example 1
Input
[1,2,3], [1,1]
Output
1
Explanation

Two cookies size 1. Only child with greed 1 is content.

Example 2
Input
[3,2,1], [1,2,3]
Output
3
Explanation

All children get cookies.

Example 3
Input
[1], []
Output
0
Explanation

No cookies.

Example 4
Input
[10,9,8,7], [5,6,7,8]
Output
2
Explanation

Children 8 and 7 get cookies 8 and 7.

Example 5
Input
[1,2], [1,2,3]
Output
2
Explanation

Both children get cookies.

Algorithm Flow

Recommendation Algorithm Flow for Assign Cookies
Recommendation Algorithm Flow for Assign Cookies

Solution Approach

Sort both arrays. Use two pointers: for each child, find smallest sufficient cookie.

function solution(g, s) {
  g.sort(function(a,b){return a-b;});
  s.sort(function(a,b){return a-b;});
  var i = 0, j = 0;
  while (i < g.length && j < s.length) {
    if (s[j] >= g[i]) i++;
    j++;
  }
  return i;
}

Time O(n log n), Space O(1).

Best Answers

java
import java.util.*;
class Solution {
    public int solution(int[] g, int[] s) {
        Arrays.sort(g);Arrays.sort(s);
        int i=0,j=0;
        while (i<g.length&&j<s.length) {
            if (s[j]>=g[i]) i++;
            j++;
        }
        return i;
    }
}