Candy (LeetCode 135): Solution and Explanation

Hard
Array
Greedy

Children stand in a row, each with a rating. Every child gets at least one candy, and any child rated higher than an adjacent neighbor must get more candies than that neighbor. Return the fewest candies needed in total.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A brute-force approach starts everyone at one candy and keeps sweeping the row, bumping any child who violates the rule, until a full sweep changes nothing. It converges, but a long descending run can need a sweep per child, so it degrades to O(n²).

The key observation is that the constraint has two independent directions. Each child must beat their left neighbor if rated higher, and must beat their right neighbor if rated higher. Each direction on its own is easy to satisfy greedily: walking left to right, a child rated above the left neighbor gets one more than that neighbor, otherwise just 1. Walking right to left handles the right-neighbor rule the same way.

To satisfy both at once, a child needs at least the larger of the two requirements. So the second pass takes max(candies[i], candies[i + 1] + 1) instead of overwriting the value, which keeps whatever the first pass established. Because each pass only gives the minimum its direction demands, the final total is the smallest possible. It helps to picture the ratings as a mountain range: the first pass climbs every upward slope from the left, the second climbs every downward slope from the right, and each peak takes the taller of the two climbs that meet there.

Approach: Two-pass greedy

  1. Start with candies = [1] * n, since every child gets at least one.
  2. Walk left to right from index 1. If ratings[i] > ratings[i - 1], set candies[i] = candies[i - 1] + 1.
  3. Walk right to left from index n - 2. If ratings[i] > ratings[i + 1], set candies[i] = max(candies[i], candies[i + 1] + 1).
  4. Leave equal neighbors alone in both passes, since equal ratings impose no ordering, which lets the count drop back to 1 right after a plateau.
  5. Return sum(candies).

Step-by-step example

ratings = [1, 3, 4, 5, 2]
  1. Start with candies = [1, 1, 1, 1, 1].
  2. Left to right: 3 > 1 gives 2, 4 > 3 gives 3, 5 > 4 gives 4, and 2 < 5 keeps 1. Now candies = [1, 2, 3, 4, 1].
  3. Right to left: at index 3, rating 5 > 2, so max(4, 1 + 1) = 4, unchanged. Indices 2, 1 and 0 are each rated lower than their right neighbor, so nothing changes.
  4. The max mattered at index 3: overwriting with candies[4] + 1 = 2 would have broken the rule against index 2.
  5. The sum is 1 + 2 + 3 + 4 + 1 = 11.

Code: Python, Java, C++

1class Solution:
2    def candy(self, ratings: List[int]) -> int:
3        n = len(ratings)
4        candies = [1] * n
5
6        # Left to right pass
7        for i in range(1, n):
8            if ratings[i] > ratings[i - 1]:
9                candies[i] = candies[i - 1] + 1
10
11        # Right to left pass
12        for i in range(n - 2, -1, -1):
13            if ratings[i] > ratings[i + 1]:
14                candies[i] = max(candies[i], candies[i + 1] + 1)
15
16        return sum(candies)

Time and space complexity

Time

O(n)

Two linear passes plus a sum, each touching every child once.

Space

O(n)

The candies array holds one count per child.

Other approaches

Repeated relaxation sweeps (time O(n²), space O(n))

Keep scanning the row and fixing violations until nothing changes. It is easy to write but can take up to n sweeps on a long decreasing run.

One pass counting slopes (time O(n), space O(1))

Track the lengths of the current increasing and decreasing runs and add arithmetic series as you go, adjusting the peak when the descent gets longer than the ascent. It needs no array but is much harder to get right.

Common mistakes

  • Overwriting in the second pass with candies[i + 1] + 1 instead of taking the max. That can drop a value the first pass needed, breaking the left-neighbor rule.
  • Treating equal ratings as needing equal candies. Neighbors with the same rating have no constraint between them, so [1, 2, 2] needs only 1 + 2 + 1 = 4 candies.
  • Doing both comparisons in a single left-to-right loop. A decreasing run is only known once you have seen its end, so one pass in one direction cannot handle it.
  • Starting the right-to-left loop at n - 1 and reading ratings[i + 1] out of range.

Frequently asked questions

Why does the candy problem need two passes?

Each child has a constraint against both neighbors, and a single direction only sees one of them. The left pass settles increasing runs, the right pass settles decreasing runs, and the max combines them.

Why is the greedy answer the minimum?

Each pass assigns the smallest value its direction requires, and the final value is the max of those two lower bounds. No valid assignment can give any child fewer, so the total is minimal.

Can the candy problem be solved in O(1) space?

Yes, by counting the lengths of rising and falling slopes in a single pass and summing them as arithmetic series. It is trickier, especially at peaks, but avoids the array.

What happens with equal adjacent ratings?

Nothing is required between them, so either child can get fewer. Both passes skip equal pairs, which lets the count reset to 1.