Rearrange Array Elements by Sign

Medium

Company Tags

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

You should return the array of nums such that the the array follows the given conditions:

  1. Every consecutive pair of integers have opposite signs.
  2. For all integers with the same sign, the order in which they were present in nums is preserved.
  3. The rearranged array begins with a positive integer.

Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

Example 1:

Input: nums = [3,1,-2,-5,2,-4]

Output: [3,-2,1,-5,2,-4]

Example 2:

Input: nums = [-1,1]

Output: [1,-1]

Constraints:

  • 2 <= nums.length <= 200,000
  • nums.length is even.
  • 1 <= |nums[i]| <= 100,000
  • nums consists of equal number of positive and negative integers.


Company Tags

Please upgrade to NeetCode Pro to view company tags.

nums =