DSA interview question
A quiz app stores a round's score changes, gains as positive numbers and penalties as negative numbers, with exactly as many of each. For the replay screen it wants them alternating, starting with a gain: positive, negative, positive, negative. It also has to keep the original order within the gains and within the penalties. Because the order within each sign must be preserved, in-place swapping gets messy; the clean O(n) solution writes positives into even indices and negatives into odd indices of a new array.
Example: [3, 1, -2, -5, 2, -4] → [3, -2, 1, -5, 2, -4].
vector<int> rearrangeBySign(const vector<int>& nums); // equal counts; starts with a positive
vector<int> rearrangeUnequal(const vector<int>& nums); // variant: leftovers appended in order
Input nums | Output | Explanation |
|---|---|---|
[3, 1, -2, -5, 2, -4] | [3, -2, 1, -5, 2, -4] | Positives 3, 1, 2 and negatives -2, -5, -4 keep their order |
[-1, 1] | [1, -1] | Must start with the positive |
[-3, -4, 5, 6] | [5, -3, 6, -4] | |
[1, 2, -4, -5, 3, 4] (unequal variant) | [1, -4, 2, -5, 3, 4] | Alternate while both remain, then append the leftover positives |
(Confirm: in the main version the counts of positives and negatives are equal and there are no zeros; relative order within each sign 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