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
INPUTMixed Array-12-345-6Negatives (red) andpositives (green) mixedALGORITHMSegregation Steps1Identify negatives2Collect in order3Place negatives first4Append positivesRESULTSegregated Array-1-3-6245All negatives first,then positivesKey Insight:Maintain relative order within each group while separating negatives from positivesUse either extra space O(n) for simple solution or in-place shifting for O(1) spaceTutorialsPoint - Segregate Negatives and Positives | Two Arrays Approach
Asked in
Microsoft 35 Amazon 28 Google 22
34.5K Views
Medium Frequency
~15 min Avg. Time
890 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