DSA interview question
A parent has cookies of various sizes and children with various greed factors: child i is content only with a cookie of size ≥ g[i]. Each child gets at most one cookie, and each cookie goes to at most one child. Maximise the number of content children. The greedy approach: sort both lists and give each child, from the least greedy, the smallest cookie that satisfies them. A cookie too small for the current child is too small for every greedier child too, so it can be thrown away.
Example: greed [1, 2, 3], cookies [1, 1] → 1.
int findContentChildren(vector<int> g, vector<int> s);
Input (greed, cookies) | Output | Explanation |
|---|---|---|
([1, 2, 3], [1, 1]) | 1 | Only the child with greed 1 |
([1, 2], [1, 2, 3]) | 2 | |
([10, 9, 8, 7], [5, 6, 7, 8]) | 2 | Cookies 7 and 8 satisfy greed 7 and 8 |
([1, 1], []) | 0 | No cookies |
([2], [1, 1]) | 0 | Cookies can't be combined |
(Confirm: each child gets at most one cookie, and cookies can't be split or combined.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in