Python coding

Most children fed

Each child has a hunger level hunger[i], and each food portion has a size portions[j]. A child is satisfied by one portion whose size is at least their hunger level. Every child gets at most one portion and every portion goes to at most one child. Return the largest number of children you can satisfy.

Both lists may be empty, and every value is a positive integer. Aim for O(n log n).

Besides the tests, one large input (3,500 children and portions) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • most_fed([1,2,3], [1,1]) → 1
  • most_fed([1,2], [1,2,3]) → 2
  • most_fed([1,3], [3,1]) → 2
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sort both lists. Once hunger levels and portions are in order, one left-to-right pass over both is enough.

Hint 2

Walk through the portions from smallest to largest. If the current one satisfies the least hungry child still waiting, give it to them; if not, it satisfies nobody, so skip it.

Hint 3

The trap is wasting big portions: handing the largest one to the first child can leave a hungrier child with nothing, as in hunger [1, 3] with portions [3, 1].

Solution and why it works
pythonO(n log n + m log m) · O(n + m)
def most_fed(hunger: list[int], portions: list[int]) -> int:
    need = sorted(hunger)
    fed = 0                              # children in need[:fed] are satisfied
    for size in sorted(portions):
        if fed < len(need) and size >= need[fed]:
            fed += 1                     # smallest portion that fits the least hungry child
    return fed

Take the smallest portion. If it can't satisfy the least hungry child, it satisfies nobody, so drop it. If it can, giving it to that child is safe: in any best assignment you can swap what that child got for this portion without losing anyone (an exchange argument). Repeat on what is left; after sorting, that is one two-pointer pass, so the sorts dominate. The trap is pairing without sorting: hunger [1, 2] with portions [2, 1], matched by position, feeds one child instead of two.