Greedy Algorithms · Coding problem

Assign Cookies

A free coding problem from the Greedy Sorted Matching skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

You're handing out cookies. Child i is happy only with a cookie of size at least greed[i], and each child gets at most one cookie. Given the cookie sizes, return the largest number of children you can make happy.

Example

Input:  greed = [3, 1, 2, 5], cookies = [2, 4, 1]
Output: 3

The cookies of size 1, 2 and 4 go to the children with greed 1, 2 and 3; the child who needs 5 misses out.

Constraints

  • 1 <= greed.length <= 10^5, 0 <= cookies.length <= 10^5
  • 1 <= greed[i], cookies[j] <= 2^31 - 1

How it's graded

  • Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

More problems in Greedy Sorted Matching

Solve it Assign Cookies free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime