712384. Assign Cookies

Easy

Assign Cookies

Summary

The "Assign Cookies" problem is an easy algorithmic challenge that involves sorting and arrays. Given two integer arrays, cookies and kids, where each element in cookies represents the number of cookies a kid wants, and each element in kids represents the age of the kids, we need to assign cookies to the kids such that the difference between the maximum and minimum number of cookies assigned is minimized. The problem requires us to write an algorithm that solves this problem efficiently.

Detailed Explanation

The key insight here is that we can sort both arrays based on their values. This allows us to pair up the smallest kid with the largest number of cookies, the second-smallest kid with the second-largest number of cookies, and so on. This way, we ensure that each kid gets at least one cookie, and the difference between the maximum and minimum number of cookies assigned is minimized.

Here's a step-by-step breakdown of the solution:

  1. Sort both cookies and kids arrays in ascending order.
  2. Initialize two pointers, i for cookies and j for kids, to the start of their respective arrays.
  3. While i is less than the length of cookies and j is less than the length of kids:
    • Assign the cookie at index i to the kid at index j.
    • Increment i and decrement j. If j becomes zero, break the loop.
  4. Return the difference between the maximum and minimum number of cookies assigned.

Time complexity: O(n log n) due to sorting Space complexity: O(1) as we only use a constant amount of space

Optimized Solutions

Java

View on GeeksforGeeks
public class AssignCookies {
    public static int assignCookies(int[] cookies, int[] kids) {
        Arrays.sort(cookies);
        Arrays.sort(kids);
        
        int i = 0, j = kids.length - 1;
        int maxDiff = 0;
        
        while (i < cookies.length && j >= 0) {
            int cookie = cookies[i];
            int kid = kids[j];
            
            if (cookie > kid) {
                return Math.abs(cookie - kid);
            }
            
            i++;
            j--;
        }
        
        return maxDiff;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.