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 Sign INPUT Original Array (nums) 3 1 -2 -5 2 -4 0 1 2 3 4 5 Positive Numbers: 3 1 2 Negative Numbers: -2 -5 -4 Length = 6 (even) 3 positive, 3 negative Equal counts guaranteed ALGORITHM STEPS 1 Initialize Two Pointers posIdx = 0 (even indices) negIdx = 1 (odd indices) 2 Create Result Array result = new int[n] Size same as input 3 Iterate and Place If num > 0: result[posIdx] posIdx += 2 If num < 0: result[negIdx] negIdx += 2 4 Return Result Alternating signs Order preserved Time: O(n) | Space: O(n) Single pass solution FINAL RESULT Output Array 3 -2 1 -5 2 -4 0 1 2 3 4 5 + - + - + - Verification: [OK] Starts with positive (3) [OK] Alternating signs [OK] Original order kept [3,-2,1,-5,2,-4] Solution Complete! Key Insight: Use two pointers: one for even indices (positive), one for odd indices (negative). By incrementing each pointer by 2, we automatically place elements at alternating positions while preserving the original order within each sign group. Single pass O(n) solution. TutorialsPoint - Rearrange Array Elements by Sign | Optimal Solution
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