Visualize

Pattern visualizer

Assign Cookies

The greedy choice is to satisfy the least demanding child with the smallest cookie that suffices. Giving a large cookie to an easily satisfied child wastes size that could satisfy a greedier child later, while giving a cookie to a child who cannot be satisfied by it wastes the cookie. By sorting both greed factors and cookie sizes, we scan both arrays with two pointers: if the current cookie satisfies the current child, we match them and move both pointers forward; otherwise, this cookie is too small for anyone remaining, so we discard it and try the next larger cookie. Animated on: g = [1, 2, 3] (greed factors), s = [1, 1] (cookie sizes) — maximize the number of content children..

Greedy smallest-cookie to smallest-greed matching

time O(n log n + m log m)space O(1)step 1 / 9
g:1
[0]
g:2
[1]
g:3
[2]
s:1
[3]
s:1
[4]
line 3

Sort both arrays. Children g=[1,2,3] at indices 0–2, cookies s=[1,1] at indices 3–4. Start pointers at child=0 (greed 1) and cookie=0 (size 1).

Pseudocode
1FUNCTION findContentChildren(g, s):
2 sort g ascending, sort s ascending
3 child = 0, cookie = 0
4 WHILE child < length of g and cookie < length of s:
5 IF s[cookie] >= g[child]:
6 move child one step forward
7 move cookie one step forward
8 RETURN child

← / → step · space play · Home restart

Where to practice Greedy