Problem 135

Abstract / Summary

Assign candies to children so each gets at least one and more than neighbors if they have higher ratings.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0135.cpp

class Solution {
public:
    int candy(vector<int>& ratings) {
        vector<int> candies(ratings.size(), 1);

        // left kid
        for (int i = 1; i < ratings.size(); i++)
            if (ratings[i] > ratings[i-1])
                candies[i] = candies[i-1]+1;

        // right kid
        for (int i = ratings.size() - 2; i >= 0; i--)
            if (ratings[i] > ratings[i+1])
                candies[i] = max(candies[i], candies[i+1]+1);

        int result = 0;
        for (auto c : candies)
            result += c;
        return result;
    }
};
21 lines | 584 bytes | submitted August 9, 2023 | GitHub   12% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic distribution problem where each element in a sequence must receive a positive integer value respecting relative ordering constraints. The algorithm proceeds in three distinct phases: an initial allocation, a forward sweep that enforces increasing relationships, and a backward sweep that resolves decreasing relationships. A final aggregation yields the total count.

Initialization

At the outset a vector named candies is created with the same length as the input ratings. Every entry is seeded with the value 1, guaranteeing the minimum requirement that each position receives at least one unit.

vector<int> candies(ratings.size(), 1);

Left-to-Right Pass

The first traversal moves from the second element to the end. Whenever the current rating exceeds the previous rating, the algorithm raises the current candy count to one more than the predecessor’s count. This step propagates the minimal increasing sequence from left to right.

for (int i = 1; i < ratings.size(); i++)
    if (ratings[i] > ratings[i-1])
        candies[i] = candies[i-1] + 1;

Right-to-Left Pass

The second traversal walks backward from the penultimate element to the start. If a rating is greater than its right neighbor, the algorithm ensures the current candy count is at least one more than the neighbor’s count, using max to preserve any larger value already assigned during the forward pass. This resolves decreasing patterns while preserving previously established increases.

for (int i = ratings.size() - 2; i >= 0; i--)
    if (ratings[i] > ratings[i+1])
        candies[i] = max(candies[i], candies[i+1] + 1);

Accumulation

After both sweeps, the vector holds the minimal valid distribution. A simple loop sums all entries to produce the final result.

int result = 0;
for (auto c : candies)
    result += c;
return result;

Edge Cases Handled

When the input contains a single element, the initialization creates a vector of length 1 with a value of 1, and both sweeps are effectively no-ops, resulting in a correct total of 1. If the ratings are strictly monotonic-either entirely increasing or entirely decreasing-the forward or backward pass respectively assigns a strictly ascending sequence of counts, while the other pass leaves the values unchanged, satisfying the ordering constraints. When adjacent ratings are equal, neither conditional in the sweeps triggers, leaving the default value of 1 for those positions, which complies with the rule that equal ratings impose no ordering requirement.

Performance Optimizations

The algorithm uses two linear passes over the data, each updating the candies vector in place without auxiliary structures, which minimizes memory overhead. The use of max in the backward pass avoids a separate comparison step, directly reconciling the two directional constraints. By initializing all entries to 1, the code eliminates the need for a separate check for the minimum requirement during the sweeps. The final aggregation employs a range-based loop, which the compiler can efficiently translate into a tight iteration. Overall, the solution achieves the desired outcome with a compact memory footprint and a constant number of passes proportional to the input size.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a row of children standing in a line, and each child has a certain number of stars representing how well they did on a drawing. You want to give them candies, but you have two special rules to make sure everyone feels happy. First, every child must get at least one candy. Second, if a child has more stars than the person standing to their left or their right, they must get more candies than that neighbor.

To solve this, first start by giving everyone just one candy. Then, walk down the line from the left side to the right side. Every time a child has more stars than the person on their left, give them one more candy than the neighbor has.

After that, walk down the line backwards starting from the right side. If a child has more stars than the person on their right, check to see if they have enough candies. If they have a smaller number of candies than the person on their right, give them one more candy than the neighbor has so they stay happy.

Finally, count up all the candies you have given out in total by adding them together. This ensures every child is happy because they have more than the neighbors they outshine, while keeping the total number of candies as small as possible.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.19 | σ = 0.77

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust C# Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
50 links | 34 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Candy - Leetcode 135 - Python'
NeetCodeIO 14 mins
Candy - Leetcode 135 - Python
YouTube video 'Candy | Live Coding with Explanation | Leetcode -135'
Algorithms Made Easy 19 mins
Candy | Live Coding with Explanation | Leetcode -135
YouTube video 'Candy | Leetcode June Challenge | Leetcode 135 | Approach + Code | C++ | Python | Hindi'
Ayushi Sharma 12 mins
Candy | Leetcode June Challenge | Leetcode 135 | Approach + Code | C++ | Python | Hindi
YouTube video 'Candy | Leetcode 135'
Techdose 17 mins
Candy | Leetcode 135
YouTube video 'LeetCode 135 | Candy Problem Visually Explained | Top Interview 150'
ByteQuest 8 mins
LeetCode 135 | Candy Problem Visually Explained | Top Interview 150
YouTube video 'Candy|LeetCode 135|Daily Leetcode potd| leetcode potd TODAY |today daily leetcode problem|daily potd'
Code Thoughts 15 mins
Candy|LeetCode 135|Daily Leetcode potd| leetcode potd TODAY |today daily leetcode problem|daily potd
YouTube video '135. Candy | Daily Leetcode Challenge | September | C++ | Java'
Mayur Programming Club 7 mins
135. Candy | Daily Leetcode Challenge | September | C++ | Java
YouTube video 'Daily Leetcode #1889: Jun 02, 2025 - 135. Candy'
Programming Live with Larry 12 mins
Daily Leetcode #1889: Jun 02, 2025 - 135. Candy
YouTube video 'Candy | LeetCode 135 | Coders Camp'
Coders Camp 11 mins
Candy | LeetCode 135 | Coders Camp
YouTube video 'Daily Leetcode #1261: Sep 13, 2023 - 135. Candy'
Programming Live with Larry 18 mins
Daily Leetcode #1261: Sep 13, 2023 - 135. Candy
YouTube video 'Leetcode 135. Candy | Distribute Candies to Children Greedily | Leetcode 135 Candy Problem Explained'
StatLearn Tech 19 mins
Leetcode 135. Candy | Distribute Candies to Children Greedily | Leetcode 135 Candy Problem Explained
YouTube video '135. Candy | Leetcode Daily - Python'
Leetcode Daily 9 mins
135. Candy | Leetcode Daily - Python
YouTube video 'Daily Leetcode #453: Jun 27, 2021 - 135. Candy'
Programming Live with Larry 12 mins
Daily Leetcode #453: Jun 27, 2021 - 135. Candy
YouTube video '135 || Candy || C++ || Leetcode Daily Challenge'
CodeFreaks 11 mins
135 || Candy || C++ || Leetcode Daily Challenge
YouTube video '135. Candy | Leetcode Daily Challenge | Linear Dynamic Programming | DSA | potd'
Eye on AI and DSA 14 mins
135. Candy | Leetcode Daily Challenge | Linear Dynamic Programming | DSA | potd
YouTube video 'THE 150 | Day 15 — Candy | LeetCode 135 | Greedy Algorithm | DSA Interview Prep'
R Sai Siddhu 61 mins
THE 150 | Day 15 — Candy | LeetCode 135 | Greedy Algorithm | DSA Interview Prep
YouTube video 'Leetcode 135. Candy'
Algorithms Casts 13 mins
Leetcode 135. Candy
YouTube video 'Candy - LeetCode 135 - Python'
Alpha-Code 12 mins
Candy - LeetCode 135 - Python
YouTube video '135 Candy | Leetcode'
R Sai Siddhu 14 mins
135 Candy | Leetcode
YouTube video 'Candy | LeetCode 135 - Python'
impoldev 10 mins
Candy | LeetCode 135 - Python
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

10 easy 2 medium 15 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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