Taro Logo

Can You Eat Your Favorite Candy on Your Favorite Day?

#1 Most AskedMedium
0 views
Topics:
Arrays

You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi].

You play a game with the following rules:

  • You start eating candies on day 0.
  • You cannot eat any candy of type i unless you have eaten all candies of type i - 1.
  • You must eat at least one candy per day until you have eaten all the candies.

Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.

Return the constructed array answer.

Example 1:

Input: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]
Output: [true,false,true]
Explanation:
1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.
2- You can eat at most 4 candies each day.
   If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.
   On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.
3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.

Example 2:

Input: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]
Output: [false,true,true,false,false]

Constraints:

  • 1 <= candiesCount.length <= 105
  • 1 <= candiesCount[i] <= 105
  • 1 <= queries.length <= 105
  • queries[i].length == 3
  • 0 <= favoriteTypei < candiesCount.length
  • 0 <= favoriteDayi <= 109
  • 1 <= dailyCapi <= 109

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 ranges and data types for the values in the candy count array and the queries (e.g., can day indices or candy counts exceed standard 32-bit integer limits)?
  2. For each query `[favoriteType, favoriteDay, dailyCap]`, are the candy types and day indices 0-indexed or 1-indexed?
  3. Can the daily consumption limit (`dailyCap`) be smaller than 1, or can the `favoriteDay` be 0?
  4. Are we strictly required to eat at least one candy every single day from day 0 up to the `favoriteDay`, or can we choose to eat zero candies on certain days as long as we don't exceed the `dailyCap`?
  5. How should we handle empty inputs or malformed queries, and should the returned boolean array match the exact order of the input queries?

Brute Force Solution

Approach

This problem asks whether we can consume at least one candy of a specific type on a specified day given eating constraints. To solve this, we compute the total number of candies that exist before and up to the target type using prefix sums. Then, for each query, we determine the minimum and maximum candies eaten by the given day and check for overlap with the target candy index range.

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

  1. Construct a prefix sum array to quickly calculate the 1-based index range of each candy type.
  2. Iterate over each query containing favoriteType, favoriteDay, and dailyCap.
  3. Calculate the minimum number of candies consumed by the favorite day, which is favoriteDay plus one.
  4. Calculate the maximum number of candies consumed by the favorite day by multiplying favoriteDay plus one by dailyCap.
  5. Determine the 1-based index interval of candies belonging to favoriteType using the prefix sums.
  6. Verify whether the consumption range overlaps with the favorite candy interval and append the boolean result.

Code Implementation

def can_eat(candiesCount, queries):
    # Compute the prefix sum of candies to know total counts before each type
    prefix_sum = [0] * (len(candiesCount) + 1)
    for index in range(len(candiesCount)):
        prefix_sum[index + 1] = prefix_sum[index] + candiesCount[index]
    
    answer = []
    for favorite_type, favorite_day, daily_cap in queries:
        # Minimum candies consumed before favorite_day ends is favorite_day + 1
        min_candies_eaten = favorite_day + 1
        # Maximum candies consumed up to favorite_day is (favorite_day + 1) * daily_cap
        max_candies_eaten = (favorite_day + 1) * daily_cap
        
        first_candy_index = prefix_sum[favorite_type] + 1
        last_candy_index = prefix_sum[favorite_type + 1]
        
        # Check if the eating range overlaps with the index range of the favorite candy type
        can_reach = not (max_candies_eaten < first_candy_index or min_candies_eaten > last_candy_index)
        answer.append(can_reach)
        
    return answer

Big(O) Analysis

Time Complexity
O(N + Q) – Building the prefix sums takes O(N) time where N is the length of candiesCount, and answering each of the Q queries takes O(1) time.
Space Complexity
O(N + Q) – The prefix sum array uses O(N) auxiliary space, and the answer list storing the results for all queries takes O(Q) space.

Optimal Solution

Approach

The problem asks whether we can consume at least one candy of a specific favorite type on a specified day given a daily eating capacity. Candies must be consumed in order of their types, and at least one candy must be eaten every day. By using prefix sums, we can determine the range of total candies required to reach and completely consume candies of the target type, then check if this interval overlaps with the range of total candies we could possibly eat by that day.

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

  1. Construct a prefix sum array of candy counts to represent the 1-based indices of each candy type.
  2. Iterate through each query consisting of the favorite type, favorite day, and daily cap.
  3. Calculate the minimum number of candies that must be eaten by the favorite day, which corresponds to eating one candy per day.
  4. Calculate the maximum number of candies that could be eaten by the favorite day, which corresponds to eating at the maximum daily capacity every day.
  5. Determine the range of candies belonging to the favorite type using the prefix sums.
  6. Check whether the interval of possible candies eaten overlaps with the interval of candies of the favorite type, appending the boolean result.

Code Implementation

def can_eat(candiesCount, queries):
    # Compute the prefix sums of candy counts to quickly find ranges.
    prefix_sums = [0]
    for count in candiesCount:
        prefix_sums.append(prefix_sums[-1] + count)
    
    answers = []
    # Process each query to check if the favorite candy can be eaten on the favorite day.
    for favorite_type, favorite_day, daily_cap in queries:
        # Minimum candies consumed before favoriteDay plus at least one candy on favoriteDay.
        min_candies_needed = favorite_day + 1
        # Maximum candies consumed up to and including favoriteDay.
        max_candies_possible = (favorite_day + 1) * daily_cap
        
        type_start = prefix_sums[favorite_type] + 1
        type_end = prefix_sums[favorite_type + 1]
        
        answers.append(min_candies_needed <= type_end and max_candies_possible >= type_start)
        
    return answers

Big(O) Analysis

Time Complexity
O(N + Q) – Building the prefix sums takes O(N) time where N is the length of candiesCount. Each of the Q queries is then processed in O(1) time by querying the prefix sums and performing basic arithmetic comparisons.
Space Complexity
O(N + Q) – The prefix sum array requires O(N) additional space, and the answer list containing the results for each query requires O(Q) auxiliary space.

Edge Cases

Integer overflow during prefix sum calculation due to large candy counts up to 10^9
How to Handle:
Use 64-bit integers for the prefix sum array to prevent arithmetic overflow.
Target day is 0, representing the very first day
How to Handle:
Ensure the logic correctly checks if the favorite type starts within the valid range for day 0.
Maximum daily cap is 1, meaning exactly one candy must be eaten per day
How to Handle:
The formula must correctly treat the consumption rate as strictly one per day without division errors.
Extremely large target days where even eating at maximum capacity exceeds total available candies
How to Handle:
Compare the target day directly against the total cumulative sum of candies up to the favorite type.
Favorite candy is the very first type at index 0
How to Handle:
Handle the base case where the preceding sum is zero without causing out-of-bounds errors.
Queries requesting to eat a candy type that has a count of zero
How to Handle:
Check that the count of the favorite candy type is strictly greater than zero.
Massive input size with up to 10^5 candies and queries, causing Time Limit Exceeded
How to Handle:
Precompute prefix sums in O(N) time and answer each query in O(1) time using direct mathematical checks.
All candies concentrated in the last type with zero candies for earlier types
How to Handle:
Prefix sum construction must correctly propagate zeros so that early queries evaluate to false.
0/1 completed