Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array. The order of appearance should be maintained.
Examples:
Input : arr[] = [12, 11, -13, -5, 6, -7, 5, -3, -6]
Output : arr[] = [-13, -5, -7, -3, -6, 12, 11, 6, 5]\
Input : arr[] = [-12, 11, 0, -5, 6, -7, 5, -3, -6]
Output : arr[] = [-12, -5, -7, -3, -6, 11, 0, 6, 5]
This problem has many solutions please refer Rearrange positive and negative numbers link, but we will solve this problem with single line of code in python using Lambda Expression.
Implementation:
Approach:
- Define a function named “Rearrange” that takes an array “arr” as an argument.
- Use list comprehension to create two separate lists – one containing all negative elements in “arr” and another containing all non-negative (positive and zero) elements in “arr”.
- Concatenate the two lists in the order of negative elements first, followed by non-negative elements.
- Return the concatenated list.
- In the main section, create an array “arr” with some positive and negative numbers.
- Call the “Rearrange” function with “arr” as an argument.
- Print the returned list.
Python3
def Rearrange(arr):
return [x for x in arr if x < 0 ] + [x for x in arr if x > = 0 ]
if __name__ = = "__main__" :
arr = [ 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 ]
print (Rearrange(arr))
|
Output[-13, -5, -7, -3, -6, 12, 11, 6, 5]
Time Complexity: O(n)
We iterate over the list of elements once, so the time complexity is linear.
Space Complexity: O(n)
We create two temporary lists, so the space complexity is also linear.
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.