Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Assign cookies of sizes s to children with greed factors g (a child is content if cookie ≥ greed). Maximise content children.

Problem: Assign cookies of sizes s to children with greed factors g (a child is content if cookie ≥ greed). Maximise content children.
def content(g, s):
    g.sort(); s.sort(); i = 0
    for c in s:
        if i < len(g) and c >= g[i]:
            i += 1
    return i
print(content([1, 2, 3], [1, 1]), content([2, 5, 7], [1, 3, 6, 8]), content([10], []))
What is printed?
  1. A. 2 3 0
  2. B. 1 2 0
  3. C. 1 3 1
  4. D. 1 3 0

Correct answer: D. 1 3 0

Sort both; give each cookie (smallest first) to the least greedy unsatisfied child if it fits, otherwise discard the cookie. [2,5,7] with [1,3,6,8]: 1 fits nobody, 3 → 2, 6 → 5, 8 → 7 = 3. O(n log n + m log m).

More Coding Interview Problems questions

Exams that ask this topic