Assign Cookies

Maximum number of content children given sorted greed factors and cookie sizes — two-pointer greedy.

Easy
Time O(n log n) Space O(1)
LeetCode
3 min read
greedy sorting two-pointers

Problem#

Child i is content if you give them a cookie of size ≥ g[i]. Each child gets at most one cookie, each cookie used at most once. Maximize content children.

Examples#

  • g = [1,2,3], s = [1,1]1
  • g = [1,2], s = [1,2,3]2

Constraints#

  • 1 <= n, m <= 3 * 10^4.

Approach#

Sort both ascending. Pointer i over greed, j over cookies. For each cookie, if s[j] >= g[i] it satisfies child i → advance both, count one. Else advance only j (cookie too small for this child).

Solution#

Assign Cookies
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int i = 0, j = 0, count = 0;
while (i < (int)g.size() && j < (int)s.size()) {
if (s[j] >= g[i]) { ++i; ++count; }
++j;
}
return count;
}
};

Editorial#

Greedy works because matching the smallest possible cookie to the least-greedy unsatisfied child never wastes a cookie. Any other assignment can be rewritten in this order without losing any matches.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.