In this post we are looking at solution of 450 dsa sheets solution using python and list compression and list extend built-in function.
Given an unsorted array arr[] of size n having both negative and positive integers. The task is place all negative element at the end of array without changing the order of positive element and negative element.
Problem Link:GeeksforGeeks
Solution:
#User function Template for python3
class Solution:
def segregateElements(self, arr, n):
non_negative = [num for num in arr[:n] if num >= 0]
negative = [num for num in arr[:n] if num < 0]
# Clear the original list in-place to avoid creating a new empty list
arr.clear()
# Extend the list with non-negative and negative elements
arr.extend(non_negative)
arr.extend(negative)
If YOur learn something knew then please share this and like this page
Put Your Thought or Query Here