Can You Eat Your Favorite Candy on Your Favorite Day? - Problem
You're at the world's most exclusive candy shop with a unique eating rule system! π
Given an array candiesCount where candiesCount[i] represents the number of candies of type i you have, and a 2D array queries where each query asks: "Can I eat my favorite candy type on my favorite day?"
The candy shop has these strict rules:
- ποΈ You start eating on day 0
- π You cannot eat candy type i until you've finished all candies of type i-1
- β° You must eat at least 1 candy per day
- π« You cannot exceed your daily limit
For each query [favoriteType, favoriteDay, dailyCap], determine if it's possible to eat candy of favoriteType on favoriteDay without exceeding dailyCap candies on any day.
Return a boolean array where answer[i] is true if query i is achievable, false otherwise.
Input & Output
example_1.py β Basic Case
$
Input:
candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]
βΊ
Output:
[true, false, true]
π‘ Note:
Query 0: Can eat type 0 on day 2 with cap 2? Yes, we can eat 2 candies of type 0 each day. Query 1: Can eat type 4 on day 2 with cap 4? No, we need to finish types 0,1,2,3 first. Query 2: Can eat type 2 on day 13 with large cap? Yes, we can reach type 2 by day 13.
example_2.py β Edge Case
$
Input:
candiesCount = [5,2,6,4,1], queries = [[3,1,6],[4,10,3],[3,10,100]]
βΊ
Output:
[false, true, true]
π‘ Note:
Query 0: Cannot reach type 3 by day 1. Query 1: Can reach type 4 by day 10 with cap 3. Query 2: Can reach type 3 by day 10 with large cap.
example_3.py β Single Type
$
Input:
candiesCount = [1000000], queries = [[0,1,1000],[0,999999,1]]
βΊ
Output:
[true, true]
π‘ Note:
Both queries can eat type 0 candies within their respective day and capacity constraints.
Visualization
Tap to expand
Understanding the Visualization
1
Sequential Access
Must finish all Type i-1 candies before accessing Type i
2
Daily Constraints
Must eat 1-dailyCap candies per day
3
Range Calculation
Calculate min/max days to reach each type
4
Feasibility Check
Check if target day falls within possible range
Key Takeaway
π― Key Insight: Instead of simulating day by day, calculate the feasible range of days for each candy type using prefix sums - this transforms the problem from simulation to range checking!
Time & Space Complexity
Time Complexity
O(n + q)
O(n) to build prefix sums, O(1) per query
β Linear Growth
Space Complexity
O(n)
Space for prefix sums and result array
β‘ Linearithmic Space
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
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code