VOOZH about

URL: https://www.geeksforgeeks.org/dsa/move-ve-elements-end-order-extra-space-allowed/

⇱ Separate Negative & Positive Preserving Order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Separate Negative & Positive Preserving Order

Last Updated : 15 Apr, 2026

Given an unsorted array arr[ ] having both negative and positive integers. Place all negative elements at the end of the array without changing the order of positive elements and negative elements.

Examples:

Input: arr[] = [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]
Explanation: All negative elements [-1, -7, -5] were arranged after positive elements [1, 3, 2, 11, 6] and the relative ordering was also preserved.

Input: arr[] = [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]
Explanation: All negative elements [-5, -3, -4, -1] were arranged after positive elements [7, 9, 10, 11] and the relative ordering was also preserved.

[Expected Approach] Using a Single Array - O(n) Time and O(n) Space

The idea is to use a temporary array that first stores positives and then negatives. Finally copy temp back to arr.

For example, arr[] = [1, -1, -3, -2, 7, 5, 11, 6]

  1. Iterate through array and store only positives in a temp array, temp[] = [1, 7, 5, 11, 6]
  2. Iterate the array again and add negative elements to temp, temp[] = [1, 7, 5, 11, 6, -1, -3, -2]
  3. Copy temp[] back into the original array.

Output
1 7 5 11 6 -1 -3 -2 

Related Articles:
Rearrange positive and negative numbers with constant extra space
Alternate Rearrangement of Positives and Negatives

Comment
Article Tags: