Tensorum
LeetCode 455 · Sorting + Simple Greedy

Assign Cookies

LeetCode 455 · Easy · solution, intuition & step-by-step walkthrough

Sort both; smallest sufficient cookie per child.

EasyArrayTwo PointersGreedySortingQuicksort
24 msruntime · beats 33%
19.9 MBmemory · beats 100%
1approach
5accepted runs · last 27 May 2025

This is how I solved Assign Cookies (LeetCode 455), an easy problem from the Sorting + Simple Greedy pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Sort children by greed and cookies by size. Give each child the smallest cookie that satisfies them — using a bigger cookie than needed can only hurt a later, greedier child.

Approach

  1. 1

    Sort g and s.

  2. 2

    If the current cookie satisfies the current child, count it and move to the next child.

  3. 3

    Always move to the next cookie.

How I solved it

Greedy two pointersPythonO(n log n) time
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        student=0
        i=0
        j=0
        while i<len(g) and j<len(s):
            if s[j]>=g[i]:
                student+=1
                i+=1
            j+=1
        return student
Loading the step-through…

Assign Cookies — FAQ

What is the intuition behind Assign Cookies?

Sort children by greed and cookies by size. Give each child the smallest cookie that satisfies them — using a bigger cookie than needed can only hurt a later, greedier child.

How do you solve Assign Cookies (LeetCode 455)?

1. Sort g and s. 2. If the current cookie satisfies the current child, count it and move to the next child. 3. Always move to the next cookie.

What is the time and space complexity of Assign Cookies?

Time: O(n log n + m log m). Space: O(1). (Accepted approach: Greedy two pointers.)

What are common mistakes in Assign Cookies?

Skip cookies that are too small rather than skipping children.