DEV Community

Manoj Kumar
Manoj Kumar

Posted on

Move All Negative Elements to End – Python

🔄 Move All Negative Elements to End – Python

Hi All,

Today I solved an interesting array problem: Move all negative elements to the end of the array while maintaining order.


📌 Problem Statement

Given an array containing both positive and negative integers, move all negative elements to the end.

⚠️ Conditions:

  • Maintain the order of elements
  • Perform operation in-place
  • Do not return a new array

🔍 Examples

Example 1:

arr = [1, -1, 3, 2, -7, -5, 11, 6]
Enter fullscreen mode Exit fullscreen mode

Output:

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

Example 2:

arr = [-5, 7, -3, -4, 9, 10, -1, 11]
Enter fullscreen mode Exit fullscreen mode

Output:

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

💡 Approach

🔹 Method: Using Extra List (Stable Order)

👉 Since we must maintain order, we:

  1. Store all positive elements
  2. Store all negative elements
  3. Combine them back into original array

💻 Python Code

def move_negatives(arr):
    positives = []
    negatives = []

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

    # Modify original array (in-place)
    arr[:] = positives + negatives
Enter fullscreen mode Exit fullscreen mode

🔍 Dry Run

For:

arr = [1, -1, 3, -2]
Enter fullscreen mode Exit fullscreen mode

Steps:

  • positives → [1, 3]
  • negatives → [-1, -2]

Final array:

[1, 3, -1, -2]
Enter fullscreen mode Exit fullscreen mode

🖥️ Sample Output

Input: [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]

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

⚡ Complexity Analysis

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

🧠 Why not two-pointer swap?

👉 Normal swapping:

  • Changes order ❌
  • Not allowed in this problem

👉 This problem needs stable arrangement


✅ Conclusion

This problem helped me understand:

  • Stable partitioning
  • Maintaining order in arrays
  • In-place modification using slicing

🚀 Useful concept for real-world data processing!


Top comments (0)