DSA interview question
A space game shows asteroids in a row. Each has a size (the absolute value) and a direction: a positive value moves right, a negative one moves left, all at the same speed. When a right-mover meets a left-mover, the smaller one explodes, and if they're equal both explode. Asteroids moving the same way never meet. Report the final state. A stack of survivors models it perfectly: only a new left-mover can hit the survivors, and only the right-movers at the top of the stack, one after another.
Example: [10, 2, -5] → [10] (−5 destroys 2, then 10 destroys −5).
vector<int> asteroidCollision(const vector<int>& asteroids); // no zeros
| Input | Output | Explanation |
|---|---|---|
[5, 10, -5] | [5, 10] | 10 destroys −5 |
[8, -8] | [] | Equal sizes: both explode |
[10, 2, -5] | [10] | −5 beats 2, then loses to 10 |
[-2, -1, 1, 2] | [-2, -1, 1, 2] | Moving apart: no collisions |
[1, -2, -2, -2] | [-2, -2, -2] |
(Confirm: values are non-zero; all asteroids move at the same speed; the relative order of survivors is preserved.)
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