As reported: Microsoft SDE2 (OneDrive and SharePoint hiring drive, Jun 2025), round 1 (DSA): LeetCode Candy; an
O(n²)solution was not enough — the interviewer expectedO(n).
n children stand in a line; child i has rating ratings[i]. Give out candies so that:
- every child gets at least one candy, and
- a child with a higher rating than a neighbour gets more candies than that neighbour.
Return the minimum number of candies needed.
This is LeetCode 135 — Candy.
Example 1
ratings = [1,0,2] -> 5 (2, 1, 2)
Example 2
ratings = [1,2,2] -> 4 (1, 2, 1)
Equal neighbours have no constraint between them.
Constraints: 1 ≤ n ≤ 2·10^4; 0 ≤ ratings[i] ≤ 2·10^4.
Code runner format: one JSON value per line: ratings (LeetCode's test-case format). Implement candy(ratings); the harness prints the result.