1. Brute Force — Quadratic Linear Scan with Visited Array
Intuition
Sort the children array ascending. For each child, loop through all cookies and find the unused cookie of minimum size that is >= child greed. Mark that cookie as used and increment count.
When to apply: When N and M are small (<= 100).
Algorithm
- Step 1: Sort children g ascending.
- Step 2: Create a boolean array used of size s.length, initialized to false.
- Step 3: For each child g[i], find index bestIdx of unused cookie with minimum size >= g[i].
- Step 4: If found, mark used[bestIdx] = true and increment count.
- Step 5: Return count.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(), g.end()); vector<bool> used(s.size(), false); int content = 0; for (int greed : g) { int bestIdx = -1; for (int j = 0; j < s.size(); ++j) { if (!used[j] && s[j] >= greed) { if (bestIdx == -1 || s[j] < s[bestIdx]) { bestIdx = j; } } } if (bestIdx != -1) { used[bestIdx] = true; content++; } } return content; }}; int main() { Solution sol; vector<int> g = {1, 2, 3}; vector<int> s = {1, 1}; cout << "Content children: " << sol.findContentChildren(g, s) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N + N * M)— Sorting g takes O(N log N). Nested loops run N * M times. - Space complexity:
O(M)— Boolean used array of size M.
Why Brute Force Doesn't Scale:
With N, M = 30,000, N * M is 9 * 108 operations, which exceeds the 1-second limit. Sorting takes ~30,000 * 15 ~ 4.5 * 105 operations, running in < 10ms.
For N = 30,000 and M = 30,000: O(N log N + M log M) completes in ~8ms compared to ~5 seconds for naive O(N * M).