Bird
Raised Fist0

Given the Python function below implementing the greedy Assign Cookies solution, what is the output when g = [2, 3, 4] and s = [1, 2, 3]?

easy🧾 Trace Q3 of Q15
Greedy Algorithms - Assign Cookies
Given the Python function below implementing the greedy Assign Cookies solution, what is the output when g = [2, 3, 4] and s = [1, 2, 3]?

def findContentChildren(g, s):
    g.sort()
    s.sort()
    i = j = 0
    while i < len(g) and j < len(s):
        if s[j] >= g[i]:
            i += 1
        j += 1
    return i
A1
B3
C2
D0
Step-by-Step Solution
Solution:
  1. Step 1: Sort both arrays

    g becomes [2, 3, 4], s becomes [1, 2, 3]
  2. Step 2: Assign cookies greedily

    Check s[0]=1 < g[0]=2 (no), move j; s[1]=2 >= 2 (yes), assign cookie, i=1, j=2; s[2]=3 >= 3 (yes), assign cookie, i=2, j=3
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Number of content children = 2 [OK]
Quick Trick: Sort arrays and use two pointers to count matches [OK]
Common Mistakes:
MISTAKES
  • Assuming all children get cookies regardless of size
  • Not incrementing cookie pointer correctly
  • Returning length of cookies instead of content children
Trap Explanation:
PITFALL
  • Choosing the total number of cookies or children instead of matched count looks plausible but is incorrect.
Interviewer Note:
CONTEXT
  • Tests understanding of greedy matching and pointer increments.
Master "Assign Cookies" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes