1. Sort greed
Sort children by how big a cookie they need.
greed.sort((a, b) => a - b)Typorithm · easy
Step 1 of 8 · intro card
Greedy
Sort both arrays, then give the smallest cookie that satisfies the least greedy remaining child.
Each child has a greed factor; a cookie satisfies them only if its size meets that greed.
Sorting both lets you match the smallest sufficient cookie to the least greedy child.
A two-pointer scan advances the child pointer only when the current cookie satisfies them.
Sort greed and sizes ascending.
Advance child only on a fit.
Always scan every cookie once.
function findContentChildren(greed, sizes) {
greed.sort((a, b) => a - b);
sizes.sort((a, b) => a - b);
let child = 0;
for (let i = 0; i < sizes.length && child < greed.length; i += 1) {
if (sizes[i] >= greed[child]) {
child += 1;
}
}
return child;
}Connect each part of the code to the concept before you type.
Sort children by how big a cookie they need.
greed.sort((a, b) => a - b)Sort cookies by size so we hand out the smallest that fits.
sizes.sort((a, b) => a - b)Walk cookies; child advances only when satisfied.
for (let i = 0; i < sizes.length && child < greed.length; i += 1)Give this cookie to the current child if it meets their greed.
if (sizes[i] >= greed[child])Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputSorted greed 1,2,3 · sorted cookies 1,1
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state