Assign Cookies — LeetCode 455 Python Solution
EasyGreedyArrayTwo PointersSorting
- Problem
- #455
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(m \times \log m + n \times \log n) |
| Space | O(\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.