sagelearnai

Assign Cookies

Difficulty: Easy · Pattern: Greedy · LeetCode #455

Child i is content with a cookie of size at least g[i]. You have cookies of sizes s[j], and each child gets at most one cookie. Return the maximum number of content children.

Examples

text
g = [1,2,3], s = [1,1]    →  1
g = [1,2],   s = [1,2,3]  →  2

Hints

  1. Sort both arrays. A large cookie should not go to a child that a smaller cookie could satisfy.

Approach

Sort g and s, and use two pointers. Walk the cookies in increasing size. If the current cookie satisfies the least greedy unsatisfied child, give it to them (child++). Either way, move to the next cookie.

Exchange argument: in some optimal solution, the smallest satisfiable child gets the smallest cookie that works for them. Swapping a bigger cookie for that one never makes things worse. O(n log n) for the sort.

Complexity

Time: O(n log n + m log m). Space: O(1) besides sorting.

Python solution
def findContentChildren(g, s):
    g, s = sorted(g), sorted(s)
    child = 0
    for c in s:
        if child < len(g) and c >= g[child]:
            child += 1
    return child
JavaScript solution
function findContentChildren(g, s) {
  g = [...g].sort((a, b) => a - b); s = [...s].sort((a, b) => a - b);
  let child = 0;
  for (const c of s) if (child < g.length && c >= g[child]) child++;
  return child;
}