Assign Cookies - Problem

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.

Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j].

If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Input & Output

Example 1 — Basic Case
$ Input: g = [1,2,3], s = [1,1]
Output: 1
💡 Note: Child with greed factor 1 can be satisfied with cookie of size 1. Children with greed factors 2 and 3 cannot be satisfied with remaining cookies.
Example 2 — Perfect Match
$ Input: g = [1,2], s = [1,2,3]
Output: 2
💡 Note: Child with greed factor 1 gets cookie of size 1, child with greed factor 2 gets cookie of size 2. Both children are satisfied.
Example 3 — No Satisfaction
$ Input: g = [5,6,7], s = [1,2,3]
Output: 0
💡 Note: All children have greed factors larger than any available cookie size, so no child can be satisfied.

Constraints

  • 1 ≤ g.length ≤ 3 × 104
  • 0 ≤ s.length ≤ 3 × 104
  • 1 ≤ g[i] ≤ 231 - 1
  • 1 ≤ s[j] ≤ 231 - 1

Visualization

Tap to expand
Assign Cookies Problem INPUT Children (greed factors g[]) g=1 g=2 g=3 Cookies (sizes s[]) s=1 s=1 g = [1, 2, 3] s = [1, 1] ALGORITHM STEPS 1 Sort Both Arrays g=[1,2,3], s=[1,1] 2 Two Pointer Init i=0 (child), j=0 (cookie) 3 Match Greedily If s[j] >= g[i]: assign 4 Count Satisfied Move pointers, count++ Matching Process: i=0, j=0: s[0]=1 >= g[0]=1 OK i=1, j=1: s[1]=1 < g[1]=2 NO j=2: No more cookies! Content children: 1 FINAL RESULT Assignment Visualization Happy! g=1, s=1 Sad (g=2) Sad (g=3) Output 1 Key Insight: Greedy approach: Sort both arrays, then try to satisfy the least greedy child with the smallest sufficient cookie. This ensures we don't waste larger cookies on children who would be happy with smaller ones. TutorialsPoint - Assign Cookies | Greedy Sort and Match Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
125.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen