Candy solution explained
To hand out the fewest candies when every child gets at least one and a child rated higher than a neighbor must get more than that neighbor, make two passes. Left to right, give each child one more than the left neighbor if their rating is higher, else one. Right to left, raise a child to one more than the right neighbor when their rating is higher and they do not already have more. Summing the result gives the minimum in O(n) time.
By Evin JohnPublished 6 min read
The task, restated
Children stand in a line, each with a rating. You give each child some candies. Every child gets at least one. If a child's rating is strictly higher than the child next to them, on either side, they must receive strictly more candies than that neighbor. Return the smallest total number of candies that satisfies both rules. Neighbors with equal ratings have no constraint between them at all.
| Ratings | Candies | Total |
|---|---|---|
[1, 3, 2] | [1, 2, 1] | 4 |
[4, 4, 4] | [1, 1, 1] | 3 |
[1, 2, 3, 4] | [1, 2, 3, 4] | 10 |
[3, 2, 1, 2, 3] | [3, 2, 1, 2, 3] | 11 |
[2, 5, 5, 1] | [1, 2, 2, 1] | 6 |
What the interviewer is looking for
This problem is usually listed as hard, mostly because the first idea, a single left-to-right pass, is wrong. Interviewers watch whether you test that idea on a falling sequence, see it fail, and realize the rule has two independent halves: a left constraint and a right constraint. Then they want a clear argument that taking the larger of the two requirements at each child is both valid and minimal.
Brute force: fix violations until stable
Start everyone at one candy. Sweep the line and, wherever a higher-rated child does not have more than a neighbor, raise them to one more than that neighbor. Repeat sweeps until a sweep changes nothing. Values only go up, and each child's count is bounded by n, so it ends, but a long falling run can take about n sweeps of n children each.
def min_candies_slow(ratings):
n = len(ratings)
give = [1] * n
changed = True
while changed:
changed = False
for i in range(n):
if i > 0 and ratings[i] > ratings[i - 1] and give[i] <= give[i - 1]:
give[i] = give[i - 1] + 1
changed = True
if i < n - 1 and ratings[i] > ratings[i + 1] and give[i] <= give[i + 1]:
give[i] = give[i + 1] + 1
changed = True
return sum(give)Optimal: one pass from each side
Split the rule. The left rule says: if a child is rated higher than the one on their left, they need more than that child. A left-to-right pass satisfies it with the smallest possible numbers, because each child's requirement depends only on the child before them. The right rule is the mirror image, satisfied by a right-to-left pass.
Each child needs at least the left-pass value and at least the right-pass value. Taking the larger of the two satisfies both rules and cannot be lowered without breaking one of them, so the total is the minimum. In code you can do the second pass in place: walk from the right and raise a child only when their right neighbor forces it.
def min_candies(ratings):
n = len(ratings)
give = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
give[i] = give[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
give[i] = max(give[i], give[i + 1] + 1)
return sum(give)function minCandies(ratings) {
const n = ratings.length;
const give = new Array(n).fill(1);
for (let i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) give[i] = give[i - 1] + 1;
}
for (let i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) give[i] = Math.max(give[i], give[i + 1] + 1);
}
return give.reduce((a, b) => a + b, 0);
}Trace [1, 3, 2]: the left pass gives [1, 2, 1], since 3 is higher than 1 and 2 is lower than 3. The right pass checks index 1: 3 is higher than 2, so it needs at least 1 + 1 = 2, which it already has. The total is 4. On [3, 2, 1, 2, 3] the left pass gives [1, 1, 1, 2, 3] and the right pass lifts the front to [3, 2, 1, 2, 3].
A constant-space variant
There is also a single-pass method that counts the lengths of rising and falling runs and adds triangular numbers, adjusting the peak to the longer of its two sides. It uses O(1) extra space. It is harder to get right under pressure, so most interviewers are satisfied with the two-pass answer plus a mention that the slope method exists. This page describes it but does not code it.
Cost of each approach
| Approach | Time | Extra space |
|---|---|---|
| Fix violations until stable | O(n²) worst case | O(n) |
| Two passes | O(n) | O(n) |
| Rising and falling run lengths | O(n) | O(1) (described, not coded here) |
Edge cases to test
- One child: 1.
- All equal ratings: n candies, one each.
- A strictly rising line: 1 + 2 + ... + n.
- A strictly falling line, which a single left pass gets wrong.
- A peak with a longer slope on one side, such as
[1, 2, 5, 4, 3, 2, 1]. - Equal neighbors at a peak, as in
[2, 5, 5, 1].
Common mistakes
- Doing only the left-to-right pass.
- In the right pass, overwriting with
give[i + 1] + 1instead of taking the maximum, which breaks the left rule. - Treating equal ratings as needing equal candies. They need nothing.
- Using
>=in the rating comparison, which forces extra candies on ties. - Summing inside the second pass and missing the last child.
How to explain it out loud
Fictional example
- Candidate
- A single left-to-right pass looks tempting, but on a falling line like 3, 2, 1 it gives everyone one candy, which breaks the rule for the first child.
- Candidate
- The rule really has two parts: beat a lower left neighbor, and beat a lower right neighbor. One pass from each direction handles each part with the smallest numbers.
- Candidate
- Each child needs the larger of the two, so in the second pass I take the max. That is linear time and linear space, and there is a constant-space slope method if you want it.
Related problems
Trapping Rain Water uses the same idea of a pass from each side, combining what each direction knows. Word Pattern is a lighter problem where two-sided consistency also matters, between letters and words. H-Index is another problem that hinges on reading the rule precisely. Every walkthrough is on the coding problems hub.
Rehearsing hard problems with Natively
Candy is a good test of whether you check a first idea before coding it. In practice on Mac or Windows, Natively can read the statement from a screenshot and give a coding hint, and the transcript of your mock round shows whether you tried a falling sequence out loud or jumped straight to code. More detail is on the coding interview assistant page.
Questions people ask
How do you solve the Candy problem in O(n)?
Give everyone one candy. Pass left to right, giving a child one more than the left neighbor when rated higher. Pass right to left, raising a child to one more than the right neighbor when rated higher, keeping the larger value. Sum the result.
Why does a single pass not work?
One pass only sees one neighbor. On a falling line such as 3, 2, 1 a left-to-right pass gives everyone one candy, so the higher-rated child on the left ends up with no more than the neighbor.
Do equal ratings need equal candies?
No. The rule only applies when one rating is strictly higher than a neighbor's, so equal neighbors have no constraint.
Can Candy be solved in O(1) space?
Yes, by counting the lengths of rising and falling runs and adding triangular numbers, with the peak taking the longer side. It is harder to get right in an interview.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
