Rearrange Array Elements by Sign - Problem

Given an integer array nums with an even length containing an equal number of positive and negative integers, you need to rearrange the elements to create a perfectly alternating pattern.

Requirements:

  • ๐Ÿ”„ Every consecutive pair must have opposite signs
  • ๐Ÿ“‹ Preserve the relative order of positive numbers
  • ๐Ÿ“‹ Preserve the relative order of negative numbers
  • โž• The result must start with a positive number

Example: [3, 1, -2, -5, 2, -4] becomes [3, -2, 1, -5, 2, -4]

Think of it like organizing a debate where speakers must alternate between supporting and opposing viewpoints, while maintaining their original speaking order within each side.

Input & Output

example_1.py โ€” Basic Case
$ Input: [3,1,-2,-5,2,-4]
โ€บ Output: [3,-2,1,-5,2,-4]
๐Ÿ’ก Note: Positive numbers [3,1,2] go to even indices [0,2,4], negative numbers [-2,-5,-4] go to odd indices [1,3,5], maintaining their original relative order.
example_2.py โ€” Different Order
$ Input: [-1,1]
โ€บ Output: [1,-1]
๐Ÿ’ก Note: Simple case with one positive and one negative. Result starts with positive number at index 0.
example_3.py โ€” Larger Array
$ Input: [1,2,3,-1,-2,-3]
โ€บ Output: [1,-1,2,-2,3,-3]
๐Ÿ’ก Note: All positive numbers [1,2,3] maintain their order at even indices, all negative numbers [-1,-2,-3] maintain their order at odd indices.

Visualization

Tap to expand
L1L2F1F2L3F3Arrival OrderL1F1L2F2L3F3Dance Line (Alternating)Pos 0Pos 1Pos 2Pos 3Pos 4Pos 5Two Pointer StrategyLeader Pointer: 0 โ†’ 2 โ†’ 4Follower Pointer: 1 โ†’ 3 โ†’ 5Each maintains their group's orderwhile filling alternating positions
Understanding the Visualization
1
Identify the Pattern
Leaders (positive) go to even positions, Followers (negative) to odd positions
2
Two Pointer Placement
Use two pointers to track next available position for each type
3
Direct Assignment
Place each person directly at their designated position in one pass
Key Takeaway
๐ŸŽฏ Key Insight: Since we know the exact alternating pattern and have equal counts, we can use two pointers to directly place elements at their final positions in O(n) time, avoiding the need for multiple scans or temporary storage.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array, each element is processed once

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space for the result array, no additional data structures needed

n
2n
โšก Linearithmic Space

Constraints

  • 2 โ‰ค nums.length โ‰ค 2 ร— 105
  • nums.length is even
  • 1 โ‰ค |nums[i]| โ‰ค 105
  • nums consists of equal number of positive and negative integers
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 19
47.3K Views
Medium-High Frequency
~15 min Avg. Time
1.8K 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