CA 09 - Move All Negative Elements to end

 Move all negative elements to end

Given an unsorted array arr[ ] having both negative and positive integers. The task is to place all negative elements at the end of the array without changing the order of positive elements and negative elements.
Input : arr[] = [1, -1, 3, 2, -7, -5, 11, 6 ]
Output : [1, 3, 2, 11, 6, -1, -7, -5]
Explanation: By doing operations we separated the integers without changing the order.
Input : arr[] = [-5, 7, -3, -4, 9, 10, -1, 11]
Output : [7, 9, 10, 11, -5, -3, -4, -1]

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)

CODE:

    With the intuitive approach for the problem is by separating the positive and negatives into two separate array and then push them into the given array such that the negative elements are in the last. Thus, the order is maintained. The time complexity as well as the Space complexity will be followed.

class Solution:
    def segregateElements(self, arr):
        pos = []
        nega = []
        for i in arr:
            if i < 0:
                nega.append(i)
            else:
                pos.append(i)
        newarr = pos+nega
        for i in range(0,len(arr)):
            arr[i] = newarr[i]

Comments

Popular posts from this blog

CA 04 - Two Sum & Sorted Two Sum

CA 05 - Reverse the array

CA 21 - Basic Select SQL Queries