DSA interview question
A teacher hands out candies to children standing in a line, each with a rating. Every child gets at least one candy, and a child with a higher rating than an immediate neighbour must get more candies than that neighbour. What's the minimum total? The constraints point in two directions, so handle them in two passes. A left-to-right pass enforces "more than the left neighbour when rated higher". A right-to-left pass enforces the same for the right neighbour, taking the maximum so the first pass's constraints still hold.
Example: ratings [1, 0, 2] → 5 (candies 2, 1, 2).
long long candy(const vector<int>& ratings);
| Input | Output | Explanation |
|---|---|---|
[1, 0, 2] | 5 | 2, 1, 2 |
[1, 2, 2] | 4 | 1, 2, 1: equal neighbours need nothing |
[1, 3, 2, 2, 1] | 7 | 1, 2, 1, 2, 1 |
[5, 4, 3, 2, 1] | 15 | 5, 4, 3, 2, 1 |
[1] | 1 |
(Confirm: only strictly higher ratings than an adjacent child impose "more candy"; equal ratings impose nothing.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in