Assign Cookies solution explained

Assign Cookies is solved by sorting the children's greed values and the cookie sizes, then walking through the cookies from smallest to largest and giving each one to the least greedy child who is still waiting, if it is big enough. Every cookie that satisfies a child is the smallest one that could, which leaves larger cookies for greedier children. It takes O(n log n + m log m) time for the two sorts and a linear scan.

By Published 7 min read

The problem in plain words

A teacher has a tray of cookies of different sizes and a class of children. Each child has a minimum size that will make them happy; any cookie at least that big works, and a smaller one does not. Each child can receive one cookie at most, cookies cannot be split or combined, and some children or cookies may end up left over. How many children can the teacher make happy?

Small examples, written for this page
Child needsCookie sizesHappy childrenWhy
[1, 3, 2][1, 1]1Only the child needing 1 can be served
[2, 4][1, 3, 5]23 goes to the child needing 2, 5 to the child needing 4
[5][2, 3]0Two small cookies cannot be combined
[1, 2, 2, 3][2, 2, 3]3Three cookies, three matches
[][3]0Nobody to feed
Small examples, written for this page. Scroll sideways on a small screen.

This is usually rated easy, so the questions to ask are short: can either list be empty, can values repeat, and is it fine to sort the inputs in place? Confirming that one cookie cannot serve two children, and two cookies cannot serve one child, also avoids a misread.

Why an easy problem still gets asked

Assign Cookies shows up as a warm-up or as the first of two problems in a round. The code is a few lines, so what the interviewer listens for is the argument. Can you say which child should get which cookie, and why that choice is safe? A clear answer here is good practice for harder matching greedy problems, where the same exchange reasoning carries the whole solution.

Go through the children from least to most greedy. For each child, scan every cookie that has not been handed out and pick the smallest one that is big enough. If none fits, that child goes without, and so will every greedier child who needs at least as much. This rule is already optimal, but scanning the cookie list for each child costs O(n·m) for n children and m cookies.

def happy_children_slow(needs, cookies):
    taken = [False] * len(cookies)
    happy = 0
    for need in sorted(needs):
        pick = -1
        for j, size in enumerate(cookies):
            if not taken[j] and size >= need and (pick == -1 or size < cookies[pick]):
                pick = j
        if pick != -1:
            taken[pick] = True
            happy += 1
    return happy
Python, O(n·m): one scan of the cookies per child.

Main approach: sort both lists, match from the small end

If the cookies are also sorted, the smallest fitting cookie for the current child is simply the next cookie that is big enough, so the scan collapses into a pointer. Walk the cookies in ascending order with a pointer on the least greedy unhappy child. When a cookie meets that child's need, the child is happy and the pointer moves on. When it does not, the cookie is too small for every remaining child, since they are all at least as greedy, so throw it away and look at the next one.

def happy_children(needs, cookies):
    needs, cookies = sorted(needs), sorted(cookies)
    child = 0
    for size in cookies:
        if child < len(needs) and size >= needs[child]:
            child += 1  # this child is happy; move to the next
    return child
Python: two sorts plus one linear pass.
function happyChildren(needs, cookies) {
  const kids = [...needs].sort((a, b) => a - b);
  const sizes = [...cookies].sort((a, b) => a - b);
  let child = 0;
  for (const size of sizes) {
    if (child < kids.length && size >= kids[child]) child++;
  }
  return child;
}
JavaScript: copies are sorted with a numeric comparator.

A mirror version also works: start from the greediest child and the largest cookie, and give the largest cookie to the greediest child it can satisfy, skipping children it cannot. Both versions are correct. Pick one and explain it fully rather than switching halfway.

Why the greedy choice is safe

Take any best assignment. Let c be the least greedy child and s the smallest cookie that satisfies c. If s is unused, give it to c and put whatever c held back on the tray; the count cannot drop. If s went to another child d, then d needs at most s. Swap the two cookies. Any cookie c held must be at least s, so it still satisfies d, and s satisfies c. If c held nothing, just move s from d to c. In every case some best plan gives c the cookie s, which is exactly the greedy choice, and the same argument repeats on the children and cookies that remain.

Trace of the second example

Needs [2, 4] and cookies [1, 3, 5] are already sorted. Cookie 1 is smaller than the need of 2, so it is skipped. Cookie 3 meets the need of 2, so the first child is happy and the pointer moves to the child needing 4. Cookie 5 meets 4, so the second child is happy. The answer is 2.

Complexity

Cost for n children and m cookies
MethodTimeExtra space
Try every matchingExponentialO(n + m)
Smallest fitting cookie by scanningO(n log n + n·m)O(m) for the taken flags
Sort both, two pointersO(n log n + m log m)O(n + m) for sorted copies
Cost for n children and m cookies. Scroll sideways on a small screen.

Sorting in place drops the extra space to whatever the sort itself needs, if the caller does not mind the inputs being reordered. The scan after the sorts is O(n + m) because each pointer only moves forward.

Edge cases to test

  • No children or no cookies: the answer is 0.
  • Every cookie smaller than every need: 0.
  • More cookies than children, all large: the answer is the number of children.
  • Repeated needs and repeated sizes, such as needs [2, 2] and cookies [2, 2].
  • A cookie exactly equal to a need: it counts, so the check is greater than or equal.
  • Inputs that arrive unsorted, which is the normal case.

Mistakes that cost points

  • Sorting only one of the two lists, then matching as if both were sorted.
  • Giving the biggest cookie to the least greedy child, which wastes size that a greedier child needed.
  • Moving the child pointer on every cookie, even when the cookie is too small.
  • Using a strict greater-than, so a cookie that exactly meets a need is rejected.
  • In JavaScript, calling sort() without a comparator, so 10 lands before 9.
  • Stating the greedy rule with no reason. Even on an easy problem, one sentence of proof is expected.

How to explain it out loud

Fictional example

A clean answer for a warm-up round
Candidate
I sort the children by how big a cookie they need and the cookies by size. Then I go through cookies from small to large, keeping a pointer on the least demanding child who is still waiting.
Candidate
If the cookie is big enough for that child, I count them and move on. If not, it is too small for everyone after them too, so I skip it.
Candidate
Giving the least demanding child the smallest cookie that works keeps the big ones for children who need them. Two sorts and a linear pass, so O(n log n plus m log m).

Other problems in this set

For a step up in difficulty that keeps the sorted-pointer flavor, try Bag of Tokens, where one pointer works from each end. When you are ready for DP, Best Time to Buy and Sell Stock IV is a good next problem because greedy alone no longer works there. For broader prep, the software engineer interview questions page covers how coding rounds fit into the loop.

Practice it with Natively

Easy problems are where you can practice talking, not just coding. Natively transcribes your mock interview on your computer so you can read back whether the one-sentence proof actually came out. During practice it can also look at a screenshot of the problem and suggest an approach, which is most useful as a check after you have solved it yourself. Take a look at an AI interview assistant for Mac and Windows.

Questions people ask

How do you solve Assign Cookies?

Sort the children's needs and the cookie sizes. Walk through the cookies from smallest to largest with a pointer on the least demanding child still waiting; if a cookie is big enough for that child, count them and move the pointer. Return the count.

Why is the greedy approach correct?

Giving the least demanding child the smallest cookie that satisfies them can be swapped into any best plan without losing a child, so it never blocks a better outcome.

What is the time complexity of Assign Cookies?

O(n log n + m log m) for sorting n needs and m cookies, plus O(n + m) for the pass with two pointers.

Can you also match from the largest cookie down?

Yes. Give the largest cookie to the greediest child it can satisfy, skipping children it cannot. It gives the same count; choose one direction and explain it fully.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP