Greedy Algorithms8 sections · 316 units
Open in Course

Assign Cookies - Algorithm

Two-pointer approach

Here is the greedy algorithm:

1.1. Sort children by greed (ascending)

2.2. Sort cookies by size (ascending)

3.3. Use two pointers: one for children, one for cookies

4.4. For each cookie: if it satisfies the current child, move both pointers; otherwise, move only the cookie pointer

5.5. Count satisfied children The two-pointer technique works because both arrays are sorted. You never need to go back. Time: O(nlogn)O(n \log n). Space: O(1)O(1). The two-pointer pattern appears in many greedy algorithms. It works when both arrays are sorted and you process each element exactly once.