Segregate Negatives and Positives - Problem
Given an array of integers containing both negative and positive numbers, rearrange the array so that all negative numbers appear before all positive numbers.
The relative order of negative numbers among themselves should be maintained, and the relative order of positive numbers among themselves should also be maintained.
Example:
- Input:
[-1, 2, -3, 4, 5, -6] - Output:
[-1, -3, -6, 2, 4, 5]
Note: Zero (if present) can be treated as a positive number.
Input & Output
Example 1 — Basic Mixed Array
$
Input:
nums = [-1, 2, -3, 4, 5, -6]
›
Output:
[-1, -3, -6, 2, 4, 5]
💡 Note:
All negatives (-1, -3, -6) come first in their original order, followed by all positives (2, 4, 5) in their original order
Example 2 — All Negatives First
$
Input:
nums = [-5, -2, -1, 3, 7]
›
Output:
[-5, -2, -1, 3, 7]
💡 Note:
Already properly arranged - negatives are already before positives
Example 3 — Including Zero
$
Input:
nums = [-1, 0, -2, 3]
›
Output:
[-1, -2, 0, 3]
💡 Note:
Zero is treated as positive, so negatives (-1, -2) come first, then positives (0, 3)
Constraints
- 1 ≤ nums.length ≤ 105
- -106 ≤ nums[i] ≤ 106
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code