Rearrange Array Elements by Sign - Problem

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 array follows the given conditions:

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

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1,-2,-5,2,-4]
Output: [3,-2,1,-5,2,-4]
💡 Note: Positive numbers [3,1,2] are placed at even indices (0,2,4), negative numbers [-2,-5,-4] at odd indices (1,3,5), preserving original order within each sign.
Example 2 — Simple Case
$ Input: nums = [-1,1]
Output: [1,-1]
💡 Note: Only one positive (1) and one negative (-1). Result starts with positive at index 0, negative at index 1.
Example 3 — Multiple Elements
$ Input: nums = [1,2,-3,-4,5,-6]
Output: [1,-3,2,-4,5,-6]
💡 Note: Positives [1,2,5] maintain order at indices 0,2,4. Negatives [-3,-4,-6] maintain order at indices 1,3,5.

Constraints

  • 2 ≤ nums.length ≤ 2 × 105
  • nums.length is even
  • 1 ≤ |nums[i]| ≤ 106
  • nums consists of equal number of positive and negative integers

Visualization

Tap to expand
Rearrange Array Elements by SignInput: Mixed positive and negative numbers31-2-52-4Rearrange: Positives at even indices, negatives at odd indicesOutput: Alternating positive-negative pattern3-21-52-4012345
Understanding the Visualization
1
Input
Mixed array: [3,1,-2,-5,2,-4]
2
Process
Place positives at even indices, negatives at odd indices
3
Output
Alternating pattern: [3,-2,1,-5,2,-4]
Key Takeaway
🎯 Key Insight: Use two pointers to directly place elements at their target positions in one pass
Asked in
Microsoft 15 Amazon 12 Adobe 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen