Facebook Pixel

1431. Kids With the Greatest Number of Candies

Problem Description

You have n kids, and each kid has a certain number of candies. You're given an array candies where candies[i] represents how many candies the i-th kid currently has. You also have extraCandies that you can give to any one kid.

Your task is to determine, for each kid, whether giving them all the extraCandies would result in them having the greatest (or tied for greatest) number of candies among all kids.

Return a boolean array result where result[i] is true if giving the i-th kid all the extra candies would make them have the maximum number of candies compared to all other kids, and false otherwise.

Key points:

  • You give ALL the extraCandies to one kid at a time (not splitting them)
  • Multiple kids can have the greatest number of candies (ties are allowed)
  • You need to check this condition for each kid separately

Example: If candies = [2, 3, 5, 1, 3] and extraCandies = 3:

  • Kid 0: 2 + 3 = 5 (would tie for max) → true
  • Kid 1: 3 + 3 = 6 (would be greater than current max of 5) → true
  • Kid 2: 5 + 3 = 8 (would be greater than current max of 5) → true
  • Kid 3: 1 + 3 = 4 (less than current max of 5) → false
  • Kid 4: 3 + 3 = 6 (would be greater than current max of 5) → true

Result: [true, true, true, false, true]

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is that we need to compare each kid's potential candy count (after receiving extra candies) with the current maximum among all kids.

Think about it this way: if we want to know whether a kid can have the greatest number of candies after receiving the extras, we need to know what "greatest" means. The greatest possible number any kid currently has is simply the maximum value in the candies array.

Once we know this maximum value, the question becomes straightforward for each kid: "If I give this kid all the extra candies, will their total be at least as much as the current maximum?"

For each kid i, we need to check if: candies[i] + extraCandies >= max(candies)

Why does this work? Because:

  • No other kid is getting any extra candies when we're checking kid i
  • The best any other kid can have is the current maximum
  • If kid i with extras can match or exceed this maximum, they'll have the greatest (or tied for greatest) number of candies

This leads to a simple two-step approach:

  1. Find the maximum number of candies any kid currently has
  2. For each kid, check if their candies plus the extra candies would be at least this maximum

The elegance of this solution is that we only need to find the maximum once, then perform a simple comparison for each kid. This avoids the need to repeatedly compare with all other kids or recalculate maximums.

Solution Approach

The implementation follows a straightforward two-pass approach:

Step 1: Find the Maximum

mx = max(candies)

We first find the maximum number of candies any kid currently has using Python's built-in max() function. This gives us the threshold that each kid needs to meet or exceed to have the greatest number of candies.

Step 2: Check Each Kid with List Comprehension

return [candy + extraCandies >= mx for candy in candies]

We use a list comprehension to create our result array. For each candy value in the candies array, we:

  • Add the extraCandies to get the potential total
  • Compare this total with mx using >=
  • This comparison returns True or False for each kid

Why List Comprehension? The list comprehension [candy + extraCandies >= mx for candy in candies] is both concise and efficient. It:

  • Iterates through each element in candies
  • Performs the calculation and comparison in one expression
  • Automatically builds the boolean result array

Time and Space Complexity:

  • Time Complexity: O(n) where n is the number of kids

    • Finding the maximum: O(n)
    • Building the result array: O(n)
    • Total: O(n) + O(n) = O(n)
  • Space Complexity: O(n) for the output array (or O(1) if we don't count the output)

The solution is optimal because we must check every kid at least once to determine their result, making O(n) the best possible time complexity for this problem.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a small example with candies = [4, 2, 1, 1, 2] and extraCandies = 1.

Step 1: Find the Maximum First, we identify the maximum number of candies any kid currently has:

  • Kid 0: 4 candies
  • Kid 1: 2 candies
  • Kid 2: 1 candy
  • Kid 3: 1 candy
  • Kid 4: 2 candies

Maximum = 4 (Kid 0 has the most)

Step 2: Check Each Kid Now we check if each kid can reach or exceed this maximum of 4 when given all extra candies:

  • Kid 0: 4 + 1 = 5 ≥ 4? Yestrue

    • They already have the max, so adding extras keeps them at the top
  • Kid 1: 2 + 1 = 3 ≥ 4? Nofalse

    • Even with extras, they can't reach the current maximum
  • Kid 2: 1 + 1 = 2 ≥ 4? Nofalse

    • Still 2 candies short of the maximum
  • Kid 3: 1 + 1 = 2 ≥ 4? Nofalse

    • Same situation as Kid 2
  • Kid 4: 2 + 1 = 3 ≥ 4? Nofalse

    • Falls 1 candy short of the maximum

Result: [true, false, false, false, false]

The key insight here is that we only need to compare against the original maximum (4), not recalculate it for each kid. This makes the solution efficient - we find the max once, then do a simple addition and comparison for each kid.

Solution Implementation

1class Solution:
2    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
3        """
4        Determine which kids can have the greatest number of candies after receiving extra candies.
5      
6        Args:
7            candies: List of integers representing candies each kid currently has
8            extraCandies: Integer representing extra candies that can be given to one kid
9          
10        Returns:
11            List of booleans where True indicates the kid at that index can have 
12            the most candies after receiving all extra candies
13        """
14        # Find the maximum number of candies among all kids
15        max_candies = max(candies)
16      
17        # Check if each kid can have >= max candies after receiving extra candies
18        # A kid can have the greatest number if their total >= current maximum
19        result = [current_candies + extraCandies >= max_candies 
20                  for current_candies in candies]
21      
22        return result
23
1class Solution {
2    /**
3     * Determines which kids can have the greatest number of candies after receiving extra candies.
4     * 
5     * @param candies Array where candies[i] represents the number of candies the i-th kid has
6     * @param extraCandies The number of extra candies that can be given to each kid
7     * @return List of boolean values where result[i] is true if kid i can have the greatest
8     *         number of candies among all kids after receiving the extra candies
9     */
10    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
11        // Find the maximum number of candies among all kids
12        int maxCandies = 0;
13        for (int currentCandies : candies) {
14            maxCandies = Math.max(maxCandies, currentCandies);
15        }
16      
17        // Create result list to store whether each kid can have the greatest amount
18        List<Boolean> result = new ArrayList<>();
19      
20        // Check each kid: if their candies plus extra candies >= max, they can have the greatest
21        for (int currentCandies : candies) {
22            boolean canHaveGreatest = (currentCandies + extraCandies) >= maxCandies;
23            result.add(canHaveGreatest);
24        }
25      
26        return result;
27    }
28}
29
1class Solution {
2public:
3    vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
4        // Find the maximum number of candies any kid currently has
5        int maxCandies = *max_element(candies.begin(), candies.end());
6      
7        // Initialize result vector to store whether each kid can have the most candies
8        vector<bool> result;
9      
10        // Check each kid: if their candies plus extra candies >= max, they can have the most
11        for (int currentCandies : candies) {
12            result.push_back(currentCandies + extraCandies >= maxCandies);
13        }
14      
15        return result;
16    }
17};
18
1/**
2 * Determines which kids can have the greatest number of candies after receiving extra candies
3 * @param candies - Array where candies[i] represents the number of candies the ith kid has
4 * @param extraCandies - Number of extra candies that can be given to a kid
5 * @returns Array of booleans where result[i] is true if kid i can have the most candies
6 */
7function kidsWithCandies(candies: number[], extraCandies: number): boolean[] {
8    // Find the maximum number of candies among all kids
9    const maxCandies: number = candies.reduce((currentMax: number, candyCount: number) => 
10        Math.max(currentMax, candyCount)
11    );
12  
13    // Check if each kid can have the greatest number of candies after receiving extra candies
14    const result: boolean[] = candies.map((candyCount: number) => 
15        candyCount + extraCandies >= maxCandies
16    );
17  
18    return result;
19}
20

Time and Space Complexity

Time Complexity: O(n) where n is the length of the candies array.

  • Finding the maximum value using max(candies) requires traversing the entire array once: O(n)
  • The list comprehension [candy + extraCandies >= mx for candy in candies] iterates through the array once more: O(n)
  • Total: O(n) + O(n) = O(n)

Space Complexity: O(n) where n is the length of the candies array.

  • The variable mx stores a single integer: O(1)
  • The returned list contains n boolean values: O(n)
  • Total auxiliary space (excluding input): O(n)

Note: If we only consider extra space beyond the output array, the space complexity would be O(1) since we only use a constant amount of extra space for the mx variable.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Modifying the Original Array

A common mistake is trying to modify the candies array in place while iterating, which can lead to incorrect comparisons.

Incorrect approach:

def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
    result = []
    for i in range(len(candies)):
        candies[i] += extraCandies  # Modifying original array!
        result.append(candies[i] >= max(candies))
        candies[i] -= extraCandies  # Trying to restore
    return result

Why it's wrong: After modifying candies[i], the max(candies) calculation includes the modified value, leading to incorrect comparisons for subsequent kids.

Solution: Always work with the original values without modification, as shown in the correct implementation.

2. Recalculating Maximum in Each Iteration

Another inefficient mistake is computing the maximum inside the loop repeatedly.

Inefficient approach:

def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
    return [candy + extraCandies >= max(candies) for candy in candies]

Why it's inefficient: This recalculates max(candies) for every kid, resulting in O(n²) time complexity instead of O(n).

Solution: Calculate the maximum once before the loop and store it in a variable.

3. Using Strict Greater Than Instead of Greater Than or Equal

Forgetting that ties are allowed is a logical error.

Incorrect comparison:

def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
    mx = max(candies)
    return [candy + extraCandies > mx for candy in candies]  # Wrong: using > instead of >=

Why it's wrong: If a kid's total equals the current maximum, they should still return true since ties for the greatest count as having the maximum.

Solution: Use >= for the comparison to properly handle ties.

4. Edge Case: Empty Array

Not handling the case where candies might be empty (though most problems guarantee non-empty input).

Potential issue:

def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
    mx = max(candies)  # Raises ValueError if candies is empty
    return [candy + extraCandies >= mx for candy in candies]

Solution: Add a guard clause if empty arrays are possible:

if not candies:
    return []
mx = max(candies)
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

In a binary min heap, the minimum element can be found in:


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More