Skip to content

Hashing — Candy ​

↗ LeetCode: Candy · Hard · pattern chapter →

Asked atAmazonMetaBloomberg

Every child gets ≥1 candy; higher-rated than a neighbor must receive strictly more. Minimize total.

Example 1 — ratings=[1,0,2] → 5 (candies = 2,1,2) Example 2 — ratings=[1,2,2] → 4 (candies = 1,2,1) Example 3 — ratings=[1,3,4,5,2] → 11 (candies = 1,2,3,4,1)

Constraints — 1 ≤ n ≤ 2·10⁴. Brute enumeration is 2·10⁴ ! — impossible. Two-pass is O(n) = 2·10⁴ ops (~50 µs). Brute repeatedly scans until no changes — O(n²) worst case = 4·10⁸ ops at n=2·10⁴. Two-pass left-then-right sweep is O(n) = 2·10⁴ ops on the hot path.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — Repeated pass until stable ​

Intuition. Give everyone 1 candy. Sweep left-to-right and right-to-left repeatedly, fixing any violation. Stop when no changes.

java
int candyBrute(int[] r) {
    int n = r.length;
    int[] c = new int[n];
    Arrays.fill(c, 1);
    boolean changed = true;
    while (changed) {
        changed = false;
        for (int i = 1; i < n; i++)
            if (r[i] > r[i-1] && c[i] <= c[i-1]) { c[i] = c[i-1] + 1; changed = true; }
        for (int i = n - 2; i >= 0; i--)
            if (r[i] > r[i+1] && c[i] <= c[i+1]) { c[i] = c[i+1] + 1; changed = true; }
    }
    int s = 0; for (int x : c) s += x; return s;
}

Complexity — Time worst-case O(n²) if the ratings are strictly increasing then decreasing; Space O(n). In an interview state this, then observe that two passes are always enough.


Approach 2 — Two-pass sweep (canonical) ​

Insight. Left→right pass enforces every strictly-greater left constraint. Right→left pass enforces every strictly-greater right constraint. Take max at each position — a single 2-pass suffices because the two constraints are independent.

java
int candy(int[] ratings) {
    int n = ratings.length;
    int[] c = new int[n];
    Arrays.fill(c, 1);
    for (int i = 1; i < n; i++) if (ratings[i] > ratings[i-1]) c[i] = c[i-1] + 1;
    for (int i = n - 2; i >= 0; i--) if (ratings[i] > ratings[i+1]) c[i] = Math.max(c[i], c[i+1] + 1);
    int sum = 0; for (int x : c) sum += x;
    return sum;
}
Execution Trace
Two-pass sweep (canonical)
i100122phase = start
Step 1 / 3Initialize scan.

Complexity — Time O(n); Space O(n). Say aloud in an interview: "two-sweep = classic pattern for one-sided constraints on both sides. Same shape in Product of Array Except Self."

Approach 3 — One-pass slope counting ​

Track up-slope and down-slope lengths + current peak. Trickier but O(1) extra space.


Try it yourself ​

Complexity summary ​

ApproachTimeSpaceGrade
Repeat-until-stableO(n²) worstO(n)Reference; can TLE
Two-sweepO(n)O(n)Canonical
One-pass slopeO(n)O(1)Polish

When to use which ​

  • Standard → two-sweep.
  • O(1) space required → one-pass slope.
  • Non-strict inequality → different logic.
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help