Python 1744.py
class Solution:
def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:
# prefix sum
prefix = []
total = 0
for c in candiesCount:
total += c
prefix.append(total)
for type, day, cap in queries:
# least number of days needed to eat all lower ranked candies
# eat as many candies as possible, respecting the cap
low = 0 if type == 0 else prefix[type - 1] // cap
# highest number of days to eat all lower ranked candies plus the current candy type
# eat just one candy daily
high = prefix[type]
yield low <= day < high
Difficulty
and has an acceptance rate of about 36% (30k+ submissions).
Typical patterns to solve this problem:
- Array
- Prefix Sum
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “candy eating” decision problem by first building a cumulative count of candies for each type and then evaluating each query against two derived bounds. The core idea is to translate the constraints of daily consumption into a range of possible days on which a particular candy type could be eaten. By pre-computing a prefix sum array, the algorithm can answer each query in constant time, and it streams the results using a generator, which avoids materialising the entire answer list up front.
Prefix-sum construction
The first phase iterates over the candiesCount list, accumulating a running total and storing each intermediate sum in a new list called prefix. This array represents the total number of candies of all types up to and including the current index.
prefix = []
total = 0
for c in candiesCount:
total += c
prefix.append(total)
The prefix sum enables O(1) look-ups of the total candies before any given type, which is essential for the subsequent bound calculations.
Query processing
For each query tuple (type, day, cap), the algorithm derives two limits:
- Low bound - the earliest day on which the target candy type could possibly be eaten, assuming the eater consumes the maximum allowed number of candies per day (
cap). The calculation uses integer division of the total candies of all lower-ranked types bycap. Whentypeis zero, there are no lower-ranked candies, so the low bound is explicitly set to zero.
low = 0 if type == 0 else prefix[type - 1] // cap
- High bound - the latest day on which the target candy type could still be eaten, assuming the eater consumes only one candy per day. This bound is simply the cumulative total of candies up to the target type.
high = prefix[type]
The query result is true when the requested day falls within the half-open interval [low, high). The generator yields the boolean directly:
yield low <= day < high
Edge-case handling
The code explicitly addresses the situation where the query asks for the first candy type (type == 0). In that case, the low bound is forced to zero, avoiding an out-of-range access to prefix[-1].
Because the low bound uses integer division, any remainder from dividing the total of lower-ranked candies by cap is discarded, which correctly models the “as many as possible” consumption strategy: the eater cannot finish the lower-ranked candies earlier than the integer-rounded-down day count.
The high bound calculation inherently handles the case where the day equals the total number of candies of the target type, because the interval is half-open; a day equal to high yields False, matching the requirement that the eater must finish the target candy before exceeding the cumulative count.
Performance optimizations
The most notable optimization is the single pass creation of the prefix sum array, which transforms a potentially linear scan per query into constant-time look-ups. This reduces the overall work from O(N × Q) to O(N + Q), where N is the number of candy types and Q is the number of queries.
Using integer division (//) for the low bound avoids floating-point operations and ensures fast arithmetic on large integers.
The function returns a generator (yield) rather than building a list of booleans. This lazy evaluation means that memory consumption scales with the number of active iterators rather than the total number of queries, which is advantageous when the result set is large or when the caller consumes the output incrementally.
By keeping all auxiliary data structures (prefix and the generator state) compact and by avoiding any nested loops, the implementation achieves high throughput even for extensive input sizes.
ELI5 - Simplified Explanation
Imagine a magical candy shop where all the treats are tucked away in long rows based on their flavor colors. The shop keeps a special list to track how many candies are in each group, and it adds them up into a running total so it knows exactly how many candies exist from the very beginning up to each flavor.
When a question asks if it is possible to eat a specific flavor on a certain day, the code looks at two different boundaries. The first boundary calculates the earliest day a person could finally reach that flavor by eating as many candies as allowed every single day. The second boundary looks at the very latest day someone could still be eating that flavor by only eating one candy each day. If the day being asked about falls somewhere between that earliest possible day and the latest possible day, then it is indeed possible to enjoy that treat. The code checks every single question one by one and announces yes or no for each one.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Go | Java | Python | ||||
| Progiez | C++ | Java | Python | |||||
| github | everthis | JS | ||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1717: Maximum Score From Removing Substrings
- problem 1785: Minimum Elements to Add to Form a Given Sum
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality