hard Candy
Problem Statment
You are given ratings array of integers where ratings[i] is rating value assigned to the ith child. You are giving candies to these n children who are standing in single row.
Follow below rules to give candies to each child:
- Each child must have
at leastone candy. - Children with a
higher ratinggetmorecandies than their neighbors.
Return the minimum count of candies you require to distribute candies to the children.
Examples
-
Example 1:
- Input: ratings =
[4, 2, 3, 4] - Expected Output:
8 - Justification: The second child gets 1 candy (lowest rating), the third gets 2 candies (higher than the second), the first gets 2 (higher than the second but equal to the third), and the fourth gets 3 (highest rating).
- Input: ratings =
-
Example 2:
- Input: ratings =
[1, 1, 1] - Expected Output:
3 - Justification: All children have the same rating, so each gets 1 candy to satisfy the minimum requirement.
- Input: ratings =
-
Example 3:
- Input: ratings =
[2, 4, 2, 6, 1, 7, 8] - Expected Output:
12 - Justification: We can give candies to each child as given in [1, 2, 1, 2, 1, 2, 3], totaling 12 candies.
- Input: ratings =
Try it yourself
Try solving this question here:
✅ Solution Candy
Problem Statment
You are given ratings array of integers where ratings[i] is rating value assigned to the ith child. You are giving candies to these n children who are standing in single row.
Follow below rules to give candies to each child:
- Each child must have
at leastone candy. - Children with a
higher ratinggetmorecandies than their neighbors.
Return the minimum count of candies you require to distribute candies to the children.
Examples
-
Example 1:
- Input: ratings =
[4, 2, 3, 4] - Expected Output:
8 - Justification: The second child gets 1 candy (lowest rating), the third gets 2 candies (higher than the second), the first gets 2 (higher than the second but equal to the third), and the fourth gets 3 (highest rating).
- Input: ratings =
-
Example 2:
- Input: ratings =
[1, 1, 1] - Expected Output:
3 - Justification: All children have the same rating, so each gets 1 candy to satisfy the minimum requirement.
- Input: ratings =
-
Example 3:
- Input: ratings =
[2, 4, 2, 6, 1, 7, 8] - Expected Output:
12 - Justification: We can give candies to each child as given in [1, 2, 1, 2, 1, 2, 3], totaling 12 candies.
- Input: ratings =
Solution
To solve this problem, we'll use a two-pass strategy to ensure fairness and efficiency. Initially, we assign one candy to every child to meet the base requirement. Then, we traverse the ratings from left to right, increasing the candy count for a child if their rating is higher than the previous child's, ensuring they receive more candies than the child before them. This guarantees that the "higher rating, more candies" rule is upheld in one direction.
However, this is not enough, as we must also check this condition in the reverse direction. To do this, we then traverse the ratings from right to left, adjusting the candy counts similarly but only increasing a child's candy if doing so would not decrease the candy count already assigned from the left-to-right pass.
This method ensures all conditions are met with the minimal amount of candy distributed, taking into account the requirements from both neighboring sides.
Step-by-Step Algorithm
-
Initialize an Array:
- Create an array
candieswith the same length as theratingsarray, and fill it with 1. This ensures every child receives at least one candy initially.
- Create an array
-
First Pass (Left to Right):
- Start from the first child (index 0) and iterate through the
ratingsarray to the last child. - For each child, compare their rating with the previous child's rating.
- If the current child's rating is higher than the previous child's, increase the current child's candies by giving them one more candy than the previous child. This is done by setting
candies[i] = candies[i-1] + 1.
- Start from the first child (index 0) and iterate through the
-
Second Pass (Right to Left):
- Start from the last child (second-to-last index) and iterate through the
ratingsarray towards the first child. - For each child, compare their rating with the next child's rating (the child on their right).
- If the current child's rating is higher than the next child's and they do not already have more candies, adjust their candies. Specifically, give the current child one more candy than the next child if necessary, ensuring that
candies[i] = candies[i+1] + 1.
- Start from the last child (second-to-last index) and iterate through the
-
Calculate Total Candies:
- Sum up all the values in the
candiesarray. This total represents the minimum number of candies needed to satisfy the conditions.
- Sum up all the values in the
Algorithm Walkthrough
Let's consider the Input: ratings = [2, 4, 2, 6, 1, 7, 8]
-
Initialization:
ratings = [2, 4, 2, 6, 1, 7, 8]candies = [1, 1, 1, 1, 1, 1, 1](Each child gets at least one candy)
-
First Pass (Left to Right):
- Compare 4 to 2: Increase candies for the second child,
candies = [1, 2, 1, 1, 1, 1, 1] - Compare 2 to 4: No increase, as 2 is not greater than 4.
- Compare 6 to 2: Increase candies for the fourth child,
candies = [1, 2, 1, 2, 1, 1, 1] - Compare 1 to 6: No increase, as 1 is not greater than 6.
- Compare 7 to 1: Increase candies for the sixth child,
candies = [1, 2, 1, 2, 1, 2, 1] - Compare 8 to 7: Increase candies for the seventh child,
candies = [1, 2, 1, 2, 1, 2, 3]
- Compare 4 to 2: Increase candies for the second child,
-
Second Pass (Right to Left):
- Compare 7 to 8: No increase needed, as we're adjusting for higher ratings to the right.
- Compare 1 to 7: No increase needed, as we're adjusting for higher ratings to the right.
- Compare 6 to 1: No increase needed, as candies[3] > candies[4].
- Compare 2 to 6: No increase, as we're adjusting for higher ratings to the right.
- Compare 4 to 2: No increase needed, as the second child already has more than the third.
- Compare 2 to 4: No increase needed, as we're adjusting for higher ratings to the right.
-
Calculate Total Candies:
- Summing the
candiesarray gives us1 + 2 + 1 + 2 + 1 + 2 + 3 = 12candies needed in total.
- Summing the
Code
import java.util.Arrays;
public class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
Arrays.fill(candies, 1); // Step 1: Assign 1 candy to each child initially
// Step 2: Left to Right Pass
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
// Step 3: Right to Left Pass
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
}
}
// Step 4: Sum up all the candies
int totalCandies = 0;
for (int candy : candies) {
totalCandies += candy;
}
return totalCandies;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
System.out.println(solution.candy(new int[] { 4, 2, 3, 4 }));
// Example 2
System.out.println(solution.candy(new int[] { 1, 1, 1 }));
// Example 3
System.out.println(solution.candy(new int[] { 2, 4, 2, 6, 1, 7, 8 }));
}
}
Complexity Analysis
Time Complexity
: The algorithm involves iterating over the ratingsarray twice—once from left to right and once from right to left. Since each pass is linear with respect to the length of theratingsarray, the overall time complexity is linear,, where n is the number of children (or the length of the ratingsarray).
Space Complexity
: Additional space is required for the candiesarray, which stores the number of candies for each child. This array is the same length as theratingsarray, so the space complexity is.
🤖 Don't fully get this? Learn it with Claude
Stuck on Candy? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Candy** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Candy** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Candy**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Candy**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.