DEV Community

Tharunya K R
Tharunya K R

Posted on

Move Negative Numbers to the End of an Array

Problem

Given an unsorted array arr[] with both negative and positive integers, move all negative elements to the end without changing the order of positive and negative elements.

Do this in-place without creating a new array.
Example 1
Input: arr = [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]
Example 2
Input: arr = [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]

Approach

Use a two-step method:
Traverse the array and move positive elements forward, maintaining their relative order.
After placing all positives, fill remaining positions with negative numbers in order.

Python Code

class Solution:
def segregateElements(self, arr):
pos = []
neg = []

    for num in arr:
        if num >= 0:
            pos.append(num)
        else:
            neg.append(num)

    i = 0

    for num in pos:
        arr[i] = num
        i += 1

    for num in neg:
        arr[i] = num
        i += 1

    return arr
Enter fullscreen mode Exit fullscreen mode

Output
Output: [1, 3, 2, 11, 6, -1, -7, -5]
Output: [7, 9, 10, 11, -5, -3, -4, -1]

Top comments (0)