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
Two cookies size 1. Only child with greed 1 is content.
All children get cookies.
No cookies.
Children 8 and 7 get cookies 8 and 7.
Both children get cookies.
Algorithm Flow

Solution Approach
Sort both arrays. Use two pointers: for each child, find smallest sufficient cookie.
Time O(n log n), Space O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
