Skip to content

Rearrange Array Elements by Sign

MediumTwo Pointers
Decode it first. Clues, constraints, pattern and plan before any code.

You are given a list nums of even length with equal numbers of positive and negative integers (no zeros). Return a new list where signs alternate, starting with a positive, and where the positives keep their original relative order and so do the negatives (preserve the order).

nums = [3, 1, -2, -5, 2, -4]   →  [3, -2, 1, -5, 2, -4]
nums = [-1, 1]                 →  [1, -1]

Constraints

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