PPractick

DSA interview question

Rearrange Array Elements by Sign

Medium · Algorithms · Topics: array, two pointer

The problem

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].

Function signature

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

Test cases

Input numsOutputExplanation
[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.)

How interviewers phrase it

Clarifying questions to ask

  1. Are the counts of positives and negatives equal?
  2. Must the relative order within each sign be preserved?
  3. Is O(n) extra space allowed?
  4. Where do zeros go, if there are any?

Follow-ups to expect

  1. "Why use a separate output array?"
  2. "How do you handle unequal counts?"
  3. "Can you do it in place?"
  4. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in