Assign Cookies - Solution
Solutions and explanations
class Solution:
def findContentChildren(self, greed_factors: List[int], cookie_sizes: List[int]) -> int:
greed_factors.sort()
cookie_sizes.sort()
child_idx = 0
cookie_idx = 0
while child_idx < len(greed_factors) and cookie_idx < len(cookie_sizes):
# Give cookie if it satisfies the child's greed
if greed_factors[child_idx] <= cookie_sizes[cookie_idx]:
child_idx += 1
cookie_idx += 1
return child_idx
Complexity Analysis
Here, n is the number of children, and m is the number of cookies.
-
Time Complexity:
O(n log n + m log m)O(n log n + m log m)for sorting, plusO(n + m)for traversal → overallO(n log n + m log m)
-
Space Complexity:
O(n + m)orO(1)- Depending on the internal implementation of sorting:
O(1)if sorting is in-place, otherwiseO(n + m)
- Depending on the internal implementation of sorting: