DSA interview question
A carpenter must join n sticks into one. Joining two sticks of lengths x and y costs x + y and produces a stick of length x + y. What's the minimum total cost? Every join adds the lengths involved, and a stick's length is paid again each time its piece is joined, so long sticks should be joined as late as possible. Always join the two shortest sticks first. A min-heap does that, and this is exactly the Huffman coding construction.
Example: [1, 8, 3, 5] → 30 (1+3 = 4, 4+5 = 9, 9+8 = 17, total 4 + 9 + 17).
long long connectSticks(const vector<int>& sticks);
| Input | Output | Explanation |
|---|---|---|
[2, 4, 3] | 14 | 2+3 = 5, then 5+4 = 9: 5 + 9 |
[1, 8, 3, 5] | 30 | 4 + 9 + 17 |
[1, 1, 1, 1] | 8 | 2 + 2 + 4 |
[3, 3, 3] | 15 | 6 + 9 |
[5] | 0 | Nothing to join |
(Confirm: lengths are positive; any two sticks can be joined; the answer can exceed 32 bits.)
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