DEV Community

Mohammed Azim J
Mohammed Azim J

Posted on

Move All Negative Elements to End (Python)

Problem Statement
Given an unsorted array containing both positive and negative integers, move all negative elements to the end of the array while maintaining the order of elements.
Condition:
• Maintain order of positives and negatives
• Perform operation in-place


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

Input: arr = [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]


Objective
• Move all negative numbers to the end
• Keep original order unchanged
• Do it efficiently


Approach: Two Lists Method
Idea
• Traverse the array once
• Store:
o Positive numbers in one list
o Negative numbers in another list
• Combine them back


Python Code
arr = [1, -1, 3, 2, -7, -5, 11, 6]

positive = []
negative = []

for i in arr:
if i >= 0:
positive.append(i)
else:
negative.append(i)

arr[:] = positive + negative

print(arr)


Step-by-Step
Original:
[1, -1, 3, 2, -7, -5, 11, 6]
Positive:
[1, 3, 2, 11, 6]
Negative:
[-1, -7, -5]
Final:
[1, 3, 2, 11, 6, -1, -7, -5]


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


In-place Style (Compact)
arr = [1, -1, 3, 2, -7, -5, 11, 6]

result = [i for i in arr if i >= 0] + [i for i in arr if i < 0]
arr[:] = result

print(arr)


Edge Cases
• All positive → no change
• All negative → same order
• Mixed values → maintain order
________________________________________ Final Thoughts
• Problem focuses on stability (order preservation)
• Simple logic but important concept
• Useful in data filtering and preprocessing

Top comments (0)