Typorithm · easy

Assign Cookies

▷ Interactive algorithm labassign-cookiesgreedysortingtwo-pointersgreedy-choice
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Assign Cookies

0%

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.

Preparing algorithm lab…
01

Sort greed and sizes ascending.

02

Advance child only on a fit.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Sort greed

Sort children by how big a cookie they need.

greed.sort((a, b) => a - b)

2. Sort cookies

Sort cookies by size so we hand out the smallest that fits.

sizes.sort((a, b) => a - b)

3. Scan cookies

Walk cookies; child advances only when satisfied.

for (let i = 0; i < sizes.length && child < greed.length; i += 1)

4. Cookie fits

Give this cookie to the current child if it meets their greed.

if (sizes[i] >= greed[child])

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Assign Cookies: Visual Walkthrough & Practice · Typorithm | ApplyDjinn