Assign Cookies — LeetCode 455 Python Solution

EasyGreedyArrayTwo PointersSorting
Problem
#455
Reading time
2 min

The problem

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.

Example

Input
g = [1,2,3], s = [1,1]
Output
1
Explanation
You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.

Python solution

Python
class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        j = 0
        for i, x in enumerate(g):
            while j < len(s) and s[j] < g[i]:
                j += 1
            if j >= len(s):
                return i
            j += 1
        return len(g)

Complexity

MeasureComplexity
TimeO(m \times \log m + n \times \log n)
SpaceO(\log m + \log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 455. Assign Cookies is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 455. Assign Cookies?
LeetCode 455. Assign Cookies is rated Easy on LeetCode.
What is the time complexity of LeetCode 455. Assign Cookies?
The Python solution on this page runs in O(m \times \log m + n \times \log n).
What is the space complexity of LeetCode 455. Assign Cookies?
The Python solution on this page uses O(\log m + \log n) auxiliary space.
What topics does LeetCode 455. Assign Cookies cover?
LeetCode 455. Assign Cookies is tagged Greedy, Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview