Back to articles
Moving All Negative Elements to the End of an Array in Python

Moving All Negative Elements to the End of an Array in Python

via Dev.toSri Mahalakshmi

Problem Explanation You are given an array arr[] containing both positive and negative integers . Your task is to move all the negative elements to the end of the array while maintaining the order of positive elements . Note: The operation should be done in-place , meaning no extra array should be used. Example: 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] Method Used: Two Pointer Technique (Stable Partition) We use a pointer to track where the next positive number should go, and rearrange elements accordingly. Why This Method? Time complexity: O(n) (single traversal) Space complexity: O(1) (in-place) Maintains order of positive elements Simple and efficient Python Code with Explanation class Solution : def segregateElements ( self , arr ): pos_index = 0 pos_index keeps track of where the next positive element should be placed. for i in range ( len ( arr )): Loop through

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles