LeetCode 135: Candy is a Hard array / string problem. This Python walkthrough develops a two directional passes solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Hard |
|---|---|
| Topic | Array / String |
| Reusable pattern | two directional passes |
| Complexity | O(n) time and O(n) space |
Recognizing the pattern
Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.
For this problem specifically, give each child one candy, scan left-to-right for increasing ratings, then right-to-left for decreasing ratings while taking the larger requirement. The invariant worth writing beside the code is: After both passes every higher-rated neighbor has strictly more candy while each allocation is minimal for its slope.
Step-by-step algorithm
- Identify the input state consumed by
candy(ratings)and initialize the data required by the two directional passes pattern. - Give each child one candy, scan left-to-right for increasing ratings, then right-to-left for decreasing ratings while taking the larger requirement.
- After each update, verify the page’s central invariant: After both passes every higher-rated neighbor has strictly more candy while each allocation is minimal for its slope.
- Finish only after the boundary behavior is covered: Plateaus reset to one; peaks must satisfy both directions.
Python solution
class Solution:
def candy(self, ratings):
sweets = [1] * len(ratings)
for i in range(1, len(ratings)):
if ratings[i] > ratings[i - 1]:
sweets[i] = sweets[i - 1] + 1
for i in range(len(ratings) - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
sweets[i] = max(sweets[i], sweets[i + 1] + 1)
return sum(sweets)Reading the implementation
The main entry point is candy(ratings). The named working state includes sweets; those variables make the two directional passes state visible instead of hiding it in incidental control flow.
The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, give each child one candy, scan left-to-right for increasing ratings, then right-to-left for decreasing ratings while taking the larger requirement.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Give each child one candy, scan left-to-right for increasing ratings, then right-to-left for decreasing ratings while taking the larger requirement. Each update records the current item without invalidating earlier decisions; consequently, after both passes every higher-rated neighbor has strictly more candy while each allocation is minimal for its slope.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().candy([1,0,2]) == 5Common mistakes and edge cases
- Problem-specific boundary: Plateaus reset to one; peaks must satisfy both directions.
- Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
- Invariant check: after every update, confirm that after both passes every higher-rated neighbor has strictly more candy while each allocation is minimal for its slope.
Interview review checklist
- Explain why two directional passes matches the structure of this input.
- State the invariant in one sentence before tracing code: After both passes every higher-rated neighbor has strictly more candy while each allocation is minimal for its slope.
- Derive O(n) time and O(n) space from how many times each element or state is visited.
- Test the boundary explicitly: Plateaus reset to one; peaks must satisfy both directions.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 134. Gas Station · Next: 42. Trapping Rain Water