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
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
โ Linear Growth
Space Complexity
O(n)
Space for the result array, no additional data structures needed
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code