Rearrange Array Elements by Sign

medium

You are given a 0-indexed integer array nums of even length. It holds an equal number of positive and negative integers.

Rearrange the values so the result satisfies all three rules:

  1. Every adjacent pair has opposite signs — a positive always sits next to a negative.
  2. Within each sign, the original order is preserved — the positives appear in the same relative order they had in nums, and likewise for the negatives.
  3. The array starts with a positive integer.

Return the rearranged array. You do not need to modify nums in place.

Hints

The answer must alternate signs while keeping each sign's original order. What if you thought of the positives and the negatives as two separate sequences?
Positives land on even indices (0, 2, 4, …) and negatives on odd indices (1, 3, 5, …). Can you send each number straight to its slot?
Keep two write-pointers — one starting at 0, one at 1 — each stepping by 2 as it places a value.

Common doubts

It's a rule of the problem, and it makes the answer unique. Without it, both a positive-first and a negative-first arrangement would satisfy the other conditions.
No. The problem explicitly allows returning a new array, which is why the clean solutions allocate a fresh result of the same length.
You scan nums from left to right and place positives as you meet them, so their relative order can never change. The same holds for the negatives.

Interview follow-ups

If the output isn't counted as extra, the two-pointer scatter is already O(1) auxiliary — it uses only two index counters. A truly in-place reorder that preserves relative order is much harder and generally needs cyclic rotations.
The perfect interleave breaks. You'd need a rule for the surplus — interleave until one side runs out, then append the rest — turning it into a merge of two unequal-length sequences.

Fun facts

  • This is a two-way merge in disguise — the same interleaving move behind merging two sorted halves in merge sort.
  • The even/odd index trick reappears everywhere: splitting a linked list into odd and even nodes, parity bucketing, and building zig-zag patterns.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: nums = [3,1,-2,-5,2,-4]
Output: [3,-2,1,-5,2,-4]
The positives are [3,1,2] and the negatives are [-2,-5,-4]. Keeping each side's order and starting with a positive gives [3,-2,1,-5,2,-4].
Example 2
Input: nums = [-1,1]
Output: [1,-1]
One positive and one negative; starting with the positive gives [1,-1].
Constraints

- 2 <= nums.length <= 2 * 10^5 - nums.length is even - 1 <= |nums[i]| <= 10^5 - nums has an equal number of positive and negative integers

Solve this problem →