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?- A. 2 3 0
- B. 1 2 0
- C. 1 3 1
- 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
- Problem: A staircase has n steps; you climb 1 or 2 steps at a time. Count the distinct ways to reach the top. cpp long long ways(int n) {…
- Problem: A thief robs houses in a row but cannot rob two adjacent houses. Find the maximum loot. python def rob(a): take = skip = 0 for x…
- Problem: Same robbery, but the houses form a circle (first and last are adjacent). python def line(a): take = skip = 0 for x in a: take…
- Problem: Find the fewest coins that make an amount (−1 if impossible). python def coins(cs, amt): INF = float('inf'); dp = [0] + [INF] amt…
- Problem: Count the number of ways to make an amount from unlimited coins, where order does not matter. python def ways(cs, amt): dp = [1]…
- Problem: 0/1 knapsack with a 1-D array. The candidate below loops capacity upwards. python def wrong(w, v, W): dp = [0] (W + 1) for i in…