DEV Community

Navin S
Navin S

Posted on

๐Ÿ”„ Move All Negative Elements to End (Maintain Order)

Rearranging elements in an array while preserving order is a common and important problem in programming.
This problem focuses on separating positive and negative numbers efficiently.


๐Ÿ“Œ Problem Statement

Given an array arr[] containing both positive and negative integers:

๐Ÿ‘‰ Move all negative elements to the end
๐Ÿ‘‰ Maintain the relative order of both positive and negative elements
๐Ÿ‘‰ Perform the operation in-place


๐Ÿ” Examples

Example 1:

Input:  [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input:  [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Concept

We need to:

  • Keep positive elements in original order
  • Move negative elements to the end in same order

๐Ÿ‘‰ This is similar to a stable partition problem


๐Ÿ”„ Approach: Using Extra Space (Stable & Simple)

Step-by-Step:

  1. Create two lists:
  • One for positive elements
  • One for negative elements

    1. Traverse the array:
  • Add positives to one list

  • Add negatives to another

    1. Merge them back into the original array

๐Ÿ’ป Python Code

```python id="q7c9vx"
def move_negatives(arr):
positives = []
negatives = []

for num in arr:
    if num >= 0:
        positives.append(num)
    else:
        negatives.append(num)

# Combine and modify original array
arr[:] = positives + negatives

return arr
Enter fullscreen mode Exit fullscreen mode

Example

print(move_negatives([1, -1, 3, 2, -7, -5, 11, 6]))




---

## ๐Ÿงพ Dry Run

For:



```id="6cdm8c"
arr = [1, -1, 3, 2, -7, -5, 11, 6]
Enter fullscreen mode Exit fullscreen mode
  • Positives โ†’ [1, 3, 2, 11, 6]
  • Negatives โ†’ [-1, -7, -5]

๐Ÿ‘‰ Final โ†’ [1, 3, 2, 11, 6, -1, -7, -5]


โšก Time and Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

๐Ÿ” Alternative Approach (In-Place but Complex)

We can also solve this without extra space using a two-pointer approach, but:

โ— It may not maintain order easily
โ— Requires shifting elements (costly operations)

๐Ÿ‘‰ Hence, the extra-space approach is preferred when order must be preserved


๐Ÿงฉ Where Is This Used?

  • Data filtering
  • Stable partition problems
  • Interview questions
  • Stream processing

๐Ÿ Conclusion

To move all negative elements to the end while maintaining order, the best approach is:

โœ” Use extra space
โœ” Keep logic simple and readable
โœ” Maintain stability

Top comments (0)