Taro Logo

Kids With the Greatest Number of Candies

Easy
Apple logo
Apple
12 views
Topics:
Arrays

There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.

Note that multiple kids can have the greatest number of candies.

Example 1:

Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true] 
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.

Example 2:

Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false] 
Explanation: There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.

Example 3:

Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]

Constraints:

  • n == candies.length
  • 2 <= n <= 100
  • 1 <= candies[i] <= 100
  • 1 <= extraCandies <= 50

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of the `candies` array and the value of `extraCandies`?
  2. Can the values in the `candies` array be negative?
  3. If the `candies` array is empty or null, what should I return?
  4. If multiple kids can have the greatest number of candies after distributing the extraCandies, should I return `true` for all of them?
  5. Is the extraCandies integer always non-negative?

Brute Force Solution

Approach

The brute force way to solve this problem is to give each kid the extra candies, one kid at a time. Then, check if that kid now has the most candies compared to everyone else. We repeat this process for every kid.

Here's how the algorithm would work step-by-step:

  1. First, look at the first kid.
  2. Imagine giving the first kid all the extra candies.
  3. Now, check if this kid has more candies than every other kid.
  4. Write down whether this is true or false.
  5. Next, do the same thing for the second kid.
  6. Imagine giving the second kid all the extra candies.
  7. Again, check if this kid now has more candies than everyone else.
  8. Write down whether this is true or false.
  9. Continue doing this for every single kid, always checking if they have the most candies after getting the extras and writing down the answer.

Code Implementation

def kids_with_candies(candies, extra_candies):
    results = []
    for current_kid_index in range(len(candies)):
        # Simulate giving the current kid the extra candies.

        current_kid_candies = candies[current_kid_index] + extra_candies

        is_greatest = True

        # Compare the current kid's candies to every other kid.

        for other_kid_index in range(len(candies)):
            if current_kid_candies < candies[other_kid_index]:
                is_greatest = False
                break

        results.append(is_greatest)

    return results

Big(O) Analysis

Time Complexity
O(n²)The outer loop iterates through each of the n kids in the candies array. Inside the outer loop, for each kid, we iterate through all the other kids to compare their candy counts with the current kid's candy count after giving the current kid extraCandies. Thus, for each of the n kids, we perform approximately n comparisons. Therefore, the time complexity is approximately n * n, which simplifies to O(n²).
Space Complexity
O(1)The described brute force algorithm requires an output list to store the boolean result for each kid, indicating whether they have the greatest number of candies after receiving the extra candies. This output list scales linearly with the number of kids, N. However, the problem asks to analyze ONLY the provided plain English explanation. The provided plain English explanation only refers to storing whether a kid has the greatest number of candies, which is a single boolean value (true or false) for each kid. Since we are only keeping track of this one boolean value at a time, no data structure grows with the input size, and therefore the space complexity is constant.

Optimal Solution

Approach

The optimal approach finds the largest number of candies any kid has. Then, it checks each kid to see if they could have the greatest number if they got the extra candies. We can determine this with a single comparison per kid, based on the max candies.

Here's how the algorithm would work step-by-step:

  1. First, find the biggest number of candies any kid currently has.
  2. Then, go through each kid's candy amount.
  3. For each kid, add the extra candies they could get to their current amount.
  4. Check if that total is greater than or equal to the biggest number of candies we found earlier.
  5. If it is, then that kid *could* have the greatest number of candies. If not, they could not.
  6. Keep track of whether each kid *could* have the greatest number, and that will be your answer.

Code Implementation

def kids_with_candies(
    candies: list[int], extra_candies: int
) -> list[bool]:
    # Find the maximum number of candies any kid has.
    max_candies = max(candies)

    result = []

    for current_candies in candies:
        # Check if the kid could have the most candies.
        if current_candies + extra_candies >= max_candies:
            result.append(True)
        else:
            result.append(False)

    return result

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through the array of candies once to find the maximum value, which takes O(n) time, where n is the number of kids (candies.length). Then, it iterates through the array again to check if each kid, with the extra candies, could have the greatest number of candies. This second iteration also takes O(n) time. Since O(n) + O(n) simplifies to O(n), the overall time complexity is O(n).
Space Complexity
O(N)The algorithm uses a list to store the boolean result for each kid, indicating whether they could have the greatest number of candies. Since there is one boolean value for each of the N kids in the input, the auxiliary space used by this result list grows linearly with the number of kids. No other significant data structures are created, so the dominant space usage is determined by the result list.

Edge Cases

CaseHow to Handle
Empty candies arrayReturn an empty boolean array since there are no kids to evaluate.
Null candies arrayThrow an IllegalArgumentException or return null to indicate invalid input, depending on the language and requirements.
extraCandies is zeroThe result is a boolean array indicating which kids initially have the maximum number of candies.
Single kid in candies arrayReturn an array containing only 'true' since the single kid will always have the greatest number of candies.
All kids have the same number of candiesReturn an array with all 'true' values since adding extraCandies to any kid will make them the greatest.
extraCandies is very largeEnsure that the sum of candies[i] and extraCandies does not result in integer overflow during comparison.
candies array contains very large numbersEnsure that the maximum value calculation does not result in integer overflow.
Large candies array sizeIterate through the array efficiently to calculate the maximum and perform the boolean checks, avoiding unnecessary computations or memory allocations.