Assign Cookies
LeetCode 455 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Sort both; smallest sufficient cookie per child.
मैंने Assign Cookies (LeetCode 455) ऐसे हल किया — Sorting + Simple Greedy पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Sort children by greed and cookies by size. Give each child the smallest cookie that satisfies them — using a bigger cookie than needed can only hurt a later, greedier child.
Approach
- 1
Sort g and s.
- 2
If the current cookie satisfies the current child, count it and move to the next child.
- 3
Always move to the next cookie.
मैंने कैसे हल किया
Greedy two pointersPythonO(n log n) time
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
student=0
i=0
j=0
while i<len(g) and j<len(s):
if s[j]>=g[i]:
student+=1
i+=1
j+=1
return student
Assign Cookies — अक्सर पूछे जाने वाले प्रश्न
Assign Cookies के पीछे intuition क्या है?
Sort children by greed and cookies by size. Give each child the smallest cookie that satisfies them — using a bigger cookie than needed can only hurt a later, greedier child.
Assign Cookies (LeetCode 455) कैसे हल करें?
1. Sort g and s. 2. If the current cookie satisfies the current child, count it and move to the next child. 3. Always move to the next cookie.
Assign Cookies की time और space complexity क्या है?
Time: O(n log n + m log m)। Space: O(1)। (Accepted approach: Greedy two pointers।)
Assign Cookies में आम गलतियाँ क्या हैं?
Skip cookies that are too small rather than skipping children.