Bird
Raised Fist0

Given the following Python code for assigning cookies to children, what is the final returned value when g = [1, 2, 3] and s = [1, 1]?

easy🧾 Code Trace Q12 of Q15
Greedy Algorithms - Assign Cookies
Given the following Python code for assigning cookies to children, what is the final returned value when g = [1, 2, 3] and s = [1, 1]?
A0
B1
C2
D3
Step-by-Step Solution
  1. Step 1: Trace first iteration

    g and s sorted: g=[1,2,3], s=[1,1]. i=0, j=0, count=0. s[0]=1 ≥ g[0]=1 -> count=1, i=1, j=1.
  2. Step 2: Trace second iteration

    i=1, j=1, count=1. s[1]=1 < g[1]=2 -> j=2. Loop ends as j=2 equals len(s).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Only one cookie satisfies a child's greed [OK]
Quick Trick: Trace pointer increments carefully [OK]
Common Mistakes:
MISTAKES
  • Counting cookies not sufficient for greed
  • Off-by-one in loop conditions
  • Ignoring pointer increments
Trap Explanation:
PITFALL
  • Some think both cookies can satisfy two children, but second cookie too small for second child.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute greedy pointer logic.
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